C#中的简单SELECT会抛出“'='附近的语法不正确”

时间:2013-04-12 20:06:58

标签: c# asp.net sql sql-server

我正在尝试使用 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();

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:3)

Submission_FileName可能是字符串(varchar)字段。您需要将值包装在单引号中:

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

仍然需要使用参数化查询来抵消SQL注入。

答案 2 :(得分: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;
}