2011-12-16 11 views

答えて

1

SqlCommand.Prepare Methodbobby-tablesで述べたように使用してください。

private static void SqlCommandPrepareEx(string connectionString) 
{ 
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    { 
     connection.Open(); 
     SqlCommand command = new SqlCommand(null, connection); 

     // Create and prepare an SQL statement. 
     command.CommandText = 
      "INSERT INTO Region (RegionID, RegionDescription) " + 
      "VALUES (@id, @desc)"; 
     SqlParameter idParam = new SqlParameter("@id", SqlDbType.Int, 0); 
     SqlParameter descParam = 
      new SqlParameter("@desc", SqlDbType.Text, 100); 
     idParam.Value = 20; 
     descParam.Value = "First Region"; 
     command.Parameters.Add(idParam); 
     command.Parameters.Add(descParam); 

     // Call Prepare after setting the Commandtext and Parameters. 
     command.Prepare(); 
     command.ExecuteNonQuery(); 

     // Change parameter values and call ExecuteNonQuery. 
     command.Parameters[0].Value = 21; 
     command.Parameters[1].Value = "Second Region"; 
     command.ExecuteNonQuery(); 
    } 
} 
2

パラメータ化クエリを使用しています、任意のparametrisedクエリを使用していません。クエリがあればどこでも使用できます。ユーザーは特に気に入ったシンボルを入力することができます。

あなたはORMを使用している場合、これはかなりあなたのために処理されますが、そうでない場合は、何をする必要があると、このようなものです:

comm.CommandText = "insert into MyTable (col1, col2) values (@col1, @col2)"; 
comm.Parameters.AddWithValue("@col1", 123); 
comm.Parameters.AddWithValue("@col2", "; drop table whatever; --"); 
comm.ExecuteNonQuery(); 

クエリが100%であること広告中毒を起こしても安全です。 .NETがあなたのためのパラメータを処理するだけで、あなたはすべて設定されます。

また、varcharではなく、nvarchar(Unicode)の列を使用していることを確認してください。ユーザーがANSI文字セットの外部にシンボルを挿入する場合は、

+0

+1また、ストアドプロシージャを使用しているときでも私が従う必要がある良い練習を提案することはできますか? – Zerotoinfinity

+0

ストアドプロシージャを呼び出す場合は、特に明記したように 'comm.Prepare()'を使いたいでしょうが、それ以外の場合は、注入を避けるのがベストプラクティスです。 – Eric

関連する問題