ExecuteScalar()を使用してデータベースから整数を返そうとしています。しかし、データベース自体でクエリを実行すると、正しい答えが得られ、C#は常に0(NULL)を返します。私はid = Convert.ToInt32(command.ExecuteScalar());
を追加する前に、NULLが処理されていることを確認するエラーが出るので、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
削除するとどうなりますか?クエリテキストに? –
はい、データベースから接続文字列をコピーしたため、正しいデータベースです.-> properties-> connectionstring。 –