0

SqlDataReaderを使用してデータベースからデータを取得しようとしています

しかし、 「System.Data.SqlClient.SqlException: Incorrect syntax near '='」という構文エラーが発生し、その内容がわかりません。

これが私のコードです

cmd = new SqlCommand("Select Submission_Attachment as Path from Tasks where Submission_FileName =" + FileName, con);
reader = cmd.ExecuteReader();
while (reader.Read())
{
   FilePath = reader["Path"].ToString();
   TextBox1.Text = FilePath;
}

reader = cmd.ExecuteReader();にエラーが表示されます。

4

3 に答える 3

15

パラメーターを使用して、SQL インジェクションを回避します。

現在の文字列が一重引用符で囲まれていないため、エラーが発生しています。

string sqlText = "Select Submission_Attachment as Path from Tasks where Submission_FileName = @fileName";
cmd = new SqlCommand(sqlText, con);
cmd.Parameters.AddWithValue("@fileName", FileName);
reader = cmd.ExecuteReader();
于 2013-04-12T20:08:17.627 に答える
3

Submission_FileNameおそらく文字列 (varchar) フィールドです。値を一重引用符で囲む必要があります。

cmd = new SqlCommand("Select Submission_Attachment as Path from Tasks where Submission_FileName = '" + FileName + "'", con);

それでも、パラメーター化されたクエリを使用して SQL インジェクションに対抗する必要があります。

于 2013-04-12T20:08:39.273 に答える
0
cmd = new SqlCommand("Select Submission_Attachment as Path from Tasks where Submission_FileName = @filename", con);
cmd.Parameters.Add("@filename", SqlDbType.VarChar, [varchar length here]).Value = FileName;
reader = cmd.ExecuteReader();
while (reader.Read())
{
   FilePath = reader["Path"].ToString();
   TextBox1.Text = FilePath;
}
于 2013-04-12T20:12:45.387 に答える