如何在C#中将SELECT COUNT语句的结果作为字符串返回?

Bar*_*hen 3 c# sql-server asp.net

我想知道如何从C#中的SELECT COUNT语句返回结果.

我有一个sql语句,返回15的计数.

目前,我正在返回datareader.我能以某种方式将结果作为字符串返回吗?

    static public SqlDataReader FillDataReader(string sql, SqlParameter[] parms)
{
    SqlConnection conn = new SqlConnection(ConnectionString);
    SqlCommand cmd = new SqlCommand(sql, conn);
    SqlDataReader dr = null;
    conn.Open();
    cmd.CommandTimeout = 120; //120 seconds for the query to finish executing

    foreach (SqlParameter p in parms)
    {
        cmd.Parameters.Add(p);
    }
    try
    {
        dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    }
    catch (SqlException ex)
    {
        if (dr != null)
        {
            dr.Close();
        }
        conn.Close();


        //DBUtilExceptionHandler(ex, sql);

        throw ex;


    }
    finally
    {
    }

    return dr; //This could be null...be sure to test for that when you use it

}
Run Code Online (Sandbox Code Playgroud)

或者我可以使用不同的方法.我只是不知道应该是什么.

任何帮助表示赞赏.

这是我的选择声明:

        select count(LeadListID) from LeadLists WHERE SalesPersonID = 1
AND LeadListDateCreated BETWEEN '9/1/11' AND '10/1/11 23:59:59'
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 13

当然 - 只需使用:

int count = (int) query.ExecuteScalar();
// TODO: Decide the right culture to use etc
return count.ToString();
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 使用using语句而不是手动try/catch/finally块
  • 无论是否有错误,都应关闭连接
  • 鉴于查询的自然结果是整数,我会将其更改为返回a int,而不是a string.如果他们愿意,让调用者进行转换
  • 如果出现错误,您几乎肯定会让异常冒泡,而不是返回 null

我会把代码编写为:

public static int ExecuteScalarInt32(string sql, SqlParameter[] parms)
{
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    using (SqlCommand command = new SqlCommand(sql, conn) { Parameters = parms })
    {
        conn.Open();
        command.CommandTimeout = 120;
        return (int) command.ExecuteScalar();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您真的需要一个版本来处理任意数据读取器,您可以将其编写为:

public static T ExecuteQuery<T>(string sql, SqlParameter[] parms,
                                Func<SqlDataReader, T> projection)
{
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    using (SqlCommand command = new SqlCommand(sql, conn) { Parameters = parms })
    {
        conn.Open();
        command.CommandTimeout = 120;
        return projection(command.ExecuteReader());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后调用它:

int count = ExecuteQuery<int>(sql, parms, reader => {
                                  if (!reader.MoveNext()) {
                                      throw new SomeGoodExceptionType("No data");
                                  }
                                  return reader.GetInt32(0);
                              });
Run Code Online (Sandbox Code Playgroud)