2017-10-16 95 views
-5

我有一个查询运行并应该提取用户的名称和电子邮件地址,如果输入的代码与表中找到的匹配。该代码是另一个表上的主键,并且是名称和电子邮件表上的外键。但是,每当我运行查询时,它都会返回无效的列名'a'。无效的列名称'a'

// the variable course runs through a method to capture the 
// code from a textbox the user enters it in. 
string sql = "select * from SI where Course= " + course; 
SqlCommand command = new SqlCommand(sql, connection.con); 
SqlDataReader read = command.ExecuteReader(); 
if (read.Read()) 
{ 
    siname = read["Name"].ToString(); 
    siemail = read["Email"].ToString(); 
} 
read.Close(); 
+0

是你的专栏当然是nvarchar? –

+2

这是您应该使用参数而不是将值连接到SQL中的一个原因。另一个是SQL注入攻击。 – juharr

回答

-1

您可能需要对SQL语句添加一个单引号像

string sql = "select * from SI where Course = '" + course + "'"; 

但是,你拥有了它,现在的方式是容易SQL注入为好。理想情况下,你用sql参数执行它。

0

本陈打败了我。问题可能不会在用户输入周围使用“'。我也会建议在你的sql命令中使用参数,防止SQL注入并使它看起来更好。取而代之的

string sql = "select * from SI where Course= '" + course + "'"; 

你可以使用:

string sql = "select * from SI where Course = @course"; 

全码:

// the variable course runs through a method to capture the 
// code from a textbox the user enters it in. 
string sql = "select * from SI where Course = @course"; 
SqlCommand command = new SqlCommand(sql, connection.con); 
command.Parameters.AddWithValue("@course", course); 
SqlDataReader read = command.ExecuteReader(); 
if (read.Read()) 
{ 
    siname = read["Name"].ToString(); 
    siemail = read["Email"].ToString(); 
} 
read.Close(); 
+0

@fubo指出谢谢你,没有意识到这一点。 – Lucax

4

使用参数,而不是字符串连接,以避免注入攻击 - imaginge的course值将'' GO DROP TABLE SI GO

另一件事是使用using声明。只要代码超出范围,就会释放未使用的连接和内存。

string command= "select * from SI where Course = @course"; 
using (SqlConnection connection = new SqlConnection(connectionString)) 
{ 
    connection.Open(); 
    using (SqlCommand cmd = new SqlCommand(command, connection)) 
    { 
     cmd.Parameters.Add("@course", SqlDbType.VarChar).Value = course; 
     using (SqlDataReader reader = cmd.ExecuteReader()) 
     {       
      if (read.Read()) 
      { 
       siname = read["Name"].ToString(); 
       siemail = read["Email"].ToString(); 
      } 
     } 
    } 
}