我想從數據庫中使用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
如果刪除,該怎麼辦?在查詢文本中? –
是的,它是正確的數據庫,因爲我從數據庫 - >屬性 - >連接字符串複製了連接字符串。 –