0

我正在尝试使用SqlDataReader从我的数据库中获取数据

但是我收到一个语法错误“System.Data.SqlClient.SqlException:'=' 附近的语法不正确”,我不知道它是怎么回事。

这是我的代码

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 回答