我尝试使用ExecuteScalar()从数据库中返回一个整数。但是,当我在数据库本身上运行查询时,我得到了正确的答案,而c#始终给我返回0(空值)。我知道它返回了一个null,因为在添加id = Convert.ToInt32(command.ExecuteScalar());
之前,它会给我一个错误,告诉我要确保处理NULL。我希望它能返回3。
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;
}
}
}
try
块之前使用这行代码command.CommandType = CommandType.Text;
。 - Raktim Biswas