C# – 网站 – SQL Select语句

我想使用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) 

它似乎正在寻找一个名为我输入的列,而不是寻找实际数据。

将您的==更改为= 。 这是无效的SQL。

此外,如果txtID.Text是非数字的,那么它需要是单引号。 你不应该像这样构建你的SQL,而是使用一个参数:

 comm.CommandText = "SELECT * FROM Customers WHERE CustomerID = @CustomerID"; comm.Parameters.AddWithValue("CustomerID", txtID.Text); 

更多信息

C#using语句

SQL参考

SQL注入 (为什么你应该参数化你的查询)

看起来您的命令有问题:

 SELECT * FROM Customers WHERE CustomerID == 1 

在SQL中,您不需要使用==运算符来确保某些内容与另一个相等。

尝试:

 SELECT * FROM Customers WHERE CustomerID = 1 

此外,您可能希望阅读有关SQL注入的信息,您绑定值的方式直接来自文本框值。 这有一个巨大的安全漏洞,可能导致任意的sql命令执行。

改变这一行:

 comm.CommandText = "SELECT * FROM Customers WHERE CustomerID == " + txtID.Text; 

到这一行:

 comm.CommandText = "SELECT * FROM Customers WHERE CustomerID = @id"; comm.Parameters.AddWithValue("id", int.Parse(txtID.Text)); 

假设您的客户ID是数据库中的int。

SQL中的equals运算符只是一个=

此外,你真的不应该像这样连接SQL查询,你只是打开自己的SQL注入攻击 。 所以改成它是这样的:

 comm.CommandText = "SELECT * FROM Customers WHERE CustomerID = @CustomerId"; comm.Parameters.AddWithValue("@CustomerId", txtID.Text); 

请参阅在MSDN上停止之前停止SQL注入攻击 。

您正在使用无效的SQL。 您可以将“==”更改为“=”。

您还应该考虑将IDisposable对象包装在using语句中,以便正确处理非托管对象并正确关闭连接。

最后,考虑在SQL中使用参数,而不是连接字符串,以避免SQL注入攻击:

 string connString = @"Data Source=KIMMY-MSI\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"; string sql = "SELECT * FROM Customers WHERE CustomerID = @CustomerID"; using (SqlConnection conn = new SqlConnection(connString)) using (SqlCommand comm = new SqlCommand(sql, conn)) { comm.Connection.Open(); comm.Parameters.AddWithValue("@CustomerID", txtID.Text); using (SqlDataReader dReader = comm.ExecuteReader()) { if (dReader.HasRows == true) { Response.Write("Exists"); } } }