【发布时间】:2022-01-09 14:00:48
【问题描述】:
try
{
SqlCommand sqlCommand = new SqlCommand("SELECT COUNT(*) FROM Doctor WHERE Id = @id", sqlServerConnection);
sqlCommand.Parameters.AddWithValue("@id", id.Text);
int numberOfDoctors = (int) sqlCommand.ExecuteScalar();
if(numberOfDoctors == 1)
{
Console.WriteLine("Doctor is already in database.");
}
else
{
Console.WriteLine("There is no doctor with this Id.");
}
}
catch (Exception exc)
{
Console.WriteLine(exc);
}
我有这样的代码。我有一个与 SQL 数据库连接的应用程序。首先,sqlServerConnection 对象在代码中被正确定义。那个对象没有问题。我在数据库中有一个 Doctor 表。 ID。 Text 来自 Text 元素,它是用户输入的值。 我想确定这个输入的 id 是否已经在我的数据库中。无论哪个值 我输入我总是看到“医生已经在数据库中”。控制台中的消息。当我删除 sqlCommand 代码中的 WHERE 子句可以正常工作。但是当我添加 WHERE 子句时,我无法跟踪 这个具有给定 id 的用户是否在我的数据库中。请你帮助我好吗?谢谢 为您提前回复。祝你有美好的一天:)
【问题讨论】:
-
当没有匹配到id值的记录时,Executescalar会返回null。您应该检查返回值,而不是总是将其类型转换为 int。
-
null 转换为 int 会导致 1 吗?
-
Id列上是否有唯一/主键?它是什么数据类型? -
我能看到的唯一问题是您使用字符串而不是整数设置 id 参数,这是我假设
Id的类型。我不确定这是否会产生除this 之外的任何不利影响。我有点怀疑您显示的代码实际上并不是您正在执行的代码。 -
尝试指定参数的类型(类型 + 长度),而不是希望 AddWithValue 正确完成
标签: c# sql-server executescalar