我想使用 select 语句来查找是否存在已存在的记录。我已将代码放在下面,但它在 dReader = comm.ExecuteReader(); 处引发错误我不确定为什么。有什么帮助吗?
string connString = "Data Source=KIMMY-MSI\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
SqlDataReader dReader;
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID == " + txtID.Text;
comm.Connection.Open();
dReader = comm.ExecuteReader();
if (dReader.HasRows == true)
{
Response.Write("Exists");
}
错误:
Invalid Column Name (whatever I input)
它似乎正在寻找名为我输入的内容的列,而不是寻找实际数据。
改变你的==
to =
。这是无效的 SQL。
此外,如果 txtID.Text 是非数字,则需要用单引号引起来。您不应该像这样构建 SQL,而应使用参数:
comm.CommandText = "SELECT * FROM Customers WHERE CustomerID = @CustomerID";
comm.Parameters.AddWithValue("CustomerID", txtID.Text);
更多信息
C# using 语句
SQL参考
SQL注入(为什么你应该参数化你的查询)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)