【发布时间】:2016-08-16 03:31:33
【问题描述】:
我正在尝试使用 ExecuteScalar() 从数据库中返回一个整数。但是,当我在数据库本身上运行查询时,我得到了正确的答案,并且 c# 一直给我一个 0 (Null)。我知道它返回一个空值,因为在我添加id = Convert.ToInt32(command.ExecuteScalar()); 之前它会给我一个错误,告诉我确保处理空值。我希望它返回 3 btw。
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;
}
}
}
【问题讨论】:
-
检查连接字符串。它是否指向您正在执行查询的同一数据库?
-
如果你删除了怎么办?在查询文本中?
-
是的,它是正确的数据库,因为我从 database->properties->connectionstring 复制了连接字符串。
-
@AlbinVinoy 调试显示的代码并检查对象
connection并检查ConnectionString属性。 -
在进入
try块之前使用此行command.CommandType = CommandType.Text;。
标签: c# winforms tsql executescalar