【问题标题】:Returning multiple Row using SqlConnection in web api在 web api 中使用 SqlConnection 返回多行
【发布时间】:2017-05-01 07:38:39
【问题描述】:

我的 API:

 public ConnectionStringSettings product;
    public DbConnection connection1;
    public DbCommand cdm1;

    public void conn1(string a)
    {
        product = ConfigurationManager.ConnectionStrings["addConnection"];
        connection1 = new SqlConnection();
        connection1.ConnectionString = product.ConnectionString;
        cdm1 = connection1.CreateCommand();
        cdm1.CommandType = CommandType.Text;
        cdm1.CommandText = a;
        connection1.Open();
    }


    [Route("api/JobApi/BrowseJobs/")]
    [HttpGet]
    public  object BrowseJobs()
    {
        string  f = "";

        try
        {

            conn1(string.Format("select * from FreelancerLogin"));
            //select karim from UserPictures where username= karim
            f = cdm1.ExecuteScalar().ToString();

        }
        catch (Exception ex)
        {
            f = ex.Message.ToString();
        }
        return f;


    }

它返回像 21 这样的单个值。但我想返回像图像和 json 格式的所有行以在 angularjs 中使用。我怎样才能做到这一点?有没有其他方法可以得到我想要的结果?

【问题讨论】:

    标签: sql-server asp.net-mvc asp.net-web-api


    【解决方案1】:

    您应该使用 SqlDataReader 和 ExecuteReader 方法而不是执行标量(执行 sacal 用于更新、删除或插入 = 查询,除了键或有效结果外不返回):

        SqlDataReader reader = cdm1.ExecuteReader();
    
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
                    reader.GetString(1));
            }
        }
        else
        {
            Console.WriteLine("No rows found.");
        }
        reader.Close();
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    • 2023-03-26
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多