我想从数据库中使用ExecuteScalar()返回一个整数。但是,当我在数据库本身上运行查询时,我得到了正确的答案,并且c#始终给我一个0(空)。我知道它返回一个空,因为在我添加id = Convert.ToInt32(command.ExecuteScalar());
之前它会给我一个错误,告诉我确保处理NULL。我期待它返回3 btw。ExecuteScalar()总是返回NULL
private int getFamilyId()
{
int id = 0;
using (SqlConnection connection = new SqlConnection(Globaldata.ConnectionString))
{
using (SqlCommand command = new SqlCommand())
{
string sqlString = @"SELECT [Id] FROM [dbo].[FamilyDetails];";
command.Connection = connection;
command.CommandText = sqlString;
try
{
connection.Open();
id = Convert.ToInt32(command.ExecuteScalar());
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK);
}
finally
{
connection.Close();
}
return id;
}
}
}
检查连接字符串。它是否指向你正在执行查询的同一个数据库? – user3185569
如果删除,该怎么办?在查询文本中? –
是的,它是正确的数据库,因为我从数据库 - >属性 - >连接字符串复制了连接字符串。 –