我试图通过在刑事数据库中查找他的NIC号码来检查一个人是否有过去的犯罪记录。但是查询没有获取任何数据,尽管数据库中没有异常和相关数据,但数据读取器仍为空。
请参阅以下代码:
SqlCommand cmd5 = new SqlCommand("select * from criminal where NIC ="+nic, conn);
string nic = "null";
foreach (var person in allInvolved)
{
conn.Open();
nic = person.NIC;
dr3 = cmd5.ExecuteReader();
if (dr3.HasRows)
{ do something }
else if (!dr3.HasRows)
{ do something else}
}
变量NIC中包含正确的值,我在调试时检查了它。我不知道我哪里出错了。如果您需要有关该代码的任何其他信息,请询问。
提前致谢。
答案 0 :(得分:2)
当你这样做时:
SqlCommand cmd5 = new SqlCommand("select * from criminal where NIC ="+nic, conn);
当前nic
的当前值 ;之后将nic
更改为的内容并不重要:
nic = person.NIC;
dr3 = cmd5.ExecuteReader();
因为未使用该值。理想情况下,您应该参数化:
SqlCommand cmd5 = new SqlCommand(
"select * from criminal where NIC = @nic", conn);
var param = cmd5.Paramters.Add("nic", SqlDbType.SomethingRelevant);
// ^^^ note: I don't know what the data type is, you'll need to pick that
foreach(...) {
param.Value = ((object)person.NIC) ?? DBNull.Value;
using(var dr3 = cmd5.ExecuteReader()) {
// ...
}
}
...
另外,请注意,很多这些对象都是IDisposable
,并且应该在using
块中;或者,看看" dapper"等工具。所以你可以做以下事情:
var criminals = conn.Query<Criminal>(
"select * from criminal where NIC = @nic",
new { nic = person.NIC}).AsList();
答案 1 :(得分:1)
试试这个
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
foreach (var person in allInvolved)
{
nic = person.NIC;
cmd.CommandText = "select * from criminal where NIC ="+nic;
dr3 = cmd.ExecuteReader();
while (dr3.Read())
{
if (dr3.HasRows)
{ do something}
else if (!dr3.HasRows)
{ do something else}
}
} con.Close();