Zunair Zubair Zunair Zubair - 6 months ago 27
SQL Question

Simple SELECT in C# throws "Incorrect syntax near '='"

I am trying to get data from my database using the SqlDataReader

But I am getting a syntax error "System.Data.SqlClient.SqlException: Incorrect syntax near '='" and I don't know what its about.

Here is my code

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


There error shows at reader = cmd.ExecuteReader();

Answer

Use parameters to avoid SQL injections.

Your current string is not surrounded by single quotes, which is causing the error.

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();