2017-10-16 6 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に値を連結する代わりに、パラメーターを使用する理由の1つです。もう1つは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

使用パラメータを - courseの値は'' GO DROP TABLE SI GOだろうimaginge 。

もう1つは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(); 
      } 
     } 
    } 
}