繁体   English   中英

C#中的简单SELECT引发“'='附近的语法不正确”

[英]Simple SELECT in C# throws “Incorrect syntax near '='”

我正在尝试使用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();处显示错误

使用参数来避免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();

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

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

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

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM