获取max int值时从SqlDataReader返回0

时间:2015-09-03 08:58:17

标签: c# sqldatareader

我得到" 0"从DB的int列获取最大值时返回。每次我尝试,读者都会返回零。

SqlConnection conn3 = new SqlConnection();
conn3.ConnectionString = @"Data Source=SHUBHAM-PC\SQLEXPRESS;Initial Catalog=DB1;Persist Security Info=True;User ID=sa;Password=***********";
SqlCommand command3 = new SqlCommand();

command3.CommandText = "select max(useCountForMonth) as useCounter from tblHRRelax";           
conn3.Open();
command3.Connection = conn3;
command3.ExecuteNonQuery();

SqlDataReader reader3 = command3.ExecuteReader();
while (reader3.Read())
{
    int useCountMonth = Convert.ToInt16(reader3["useCounter"]);                           
    MessageBox.Show("Reader Value " + useCountMonth);
}
conn3.Close();

3 个答案:

答案 0 :(得分:2)

您的代码应该是这样的:

  //TODO: do not hardcode connection string here (esp. password), but load it
  String connectionString = @"Data Source=SHUBHAM-PC\SQLEXPRESS;Initial Catalog=DB1;Persist Security Info=True;User ID=sa;Password=***********";

  // wrap IDisposable into using
  using (SqlConnection conn = new SqlConnection(connectionString)) {
    conn.Open();

    // wrap IDisposable into using
    using (SqlCommand q = new SqlCommand(conn)) {
      // Make your sql being readable:
      q.CommandText =
        @"select max(useCountForMonth) as useCounter
            from tblHRRelax";

      // wrap IDisposable into using
      using (var reader = q.ExecuteReader()) {
        if (reader.Read()) // no "while" - just one value to read - "if" 
          MessageBox.Show("Reader Value " + Convert.ToString(reader[0])); // do you want Int32 or String?
      }
    }
  } 

不当行为的可能原因:

  1. 实际最大值为0 - SQL执行其工作,检查您的数据
  2. 表中没有无值(或者所有空值),并将null转换为整数0

答案 1 :(得分:0)

删除第command3.ExecuteNonQuery();行。

答案 2 :(得分:0)

该表不包含任何行,或者所有useCountForMonth列都为NULL或0.在这种情况下,MAX(useCountForMonth)将返回NULL,Convert.ToInt16将更改为0。

确保useCountForMonth列中至少有一个非空(大于零)的值。

一般来说,代码存在一些问题:

  • 不需要调用ExecuteNonQuery,您只需再次执行相同的查询并丢弃结果
  • 整数是32位。为避免不必要的转换,您应使用ToInt32