我有一个MS SQL数据库,其中有以下字段:
使用相同的businessid可以有很多行,并且具有相同的refno,可以有很多行。但是使用相同的refno和businessid,只能有一行。现在可以有许多行具有相同的businessid,但我想检查这些businessid中是否存在特定的refno。我知道如何检查表中是否存在businessid。但我很困惑如何检查具有相同名称的businessid是否具有特定的refno。
string g = Session["businessid"].ToString();
string h = Session["referenceno"].ToString();
con.Open();
SqlCommand check = new SqlCommand("select * from quoted_price where businessid=@businessid", con);
check.Parameters.AddWithValue("@businessid", g);
SqlDataReader dr = check.ExecuteReader();
if (dr.HasRows)
{
con.Close();
}
答案 0 :(得分:1)
您的代码存在一个主要问题。您没有正确处理实现IDisposable的对象。您需要使用using块或try/catch/finally模式,在finally
块中处理清理。如果不这样做会导致连接断开,以后您可能会遇到奇怪的难以诊断的错误。对于您使用的任何类(特别是在需要存储或网络访问时),请始终检查它是否实现IDisposable。
您还应该考虑何时在打开连接时创建SqlConnection vs。为什么在准备使用它之前打开连接?
此外,变量应充分描述它们包含的信息。避免使用无用的名称,例如g
和h
。
最后,您可以使用两个参数来检查您想要检查的条件。
string businessId = Session["businessid"].ToString();
string referenceNo = Session["referenceno"].ToString();
bool hasRows = false;
using(SqlConnection connection = new SqlConnection(parameters))
{
using(SqlCommand checkCommand = new SqlCommand("select * from quoted_price where businessid=@businessid AND refno=@refno", connection))
{
checkCommand.Parameters.AddWithValue("@businessid", businessId);
checkCommand.Parameters.AddWithValue("@refno", referenceNo);
connection.Open();
using(SqlDataReader dataReader = check.ExecuteReader())
{
hasRows = dataReader.HasRows;
}
}
}
请注意,不是试图用dataReader
来做很多逻辑,而是从我得到我想要的东西,并存储我关心的值。这是因为我不想让连接打开超过必要的时间。