我得到" 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();
答案 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)
删除第command3.ExecuteNonQuery();
行。
答案 2 :(得分:0)
该表不包含任何行,或者所有useCountForMonth
列都为NULL或0.在这种情况下,MAX(useCountForMonth)
将返回NULL,Convert.ToInt16
将更改为0。
确保useCountForMonth
列中至少有一个非空(大于零)的值。
一般来说,代码存在一些问题:
ExecuteNonQuery
,您只需再次执行相同的查询并丢弃结果ToInt32