2017-10-16 147 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(); 
      } 
     } 
    } 
}