andrew faz andrew faz - 1 month ago 5x
C# Question

Incorrect syntax near '= '. in code c#

I'm developing a c# windows form application program that saves the info about the student like name course year and etc. My code in saving to sql database works but when it comes to retreiving the info i get these error incorrect syntax near '='. i think the error is in the retreive code.please help :)

Here is the retrieve code:

string sql = "SELECT studnum,course,f_name,l_name,color_image FROM table3 WHERE f_name=" + textBoxfname.Text + "";
if (conn.State != ConnectionState.Open)
command = new SqlCommand(sql, conn);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
labeloutputstudnum.Text = reader[0].ToString();
labeloutputcourse.Text = reader[1].ToString();
labeloutputfname.Text = reader[2].ToString();
labeloutputlname.Text = reader[3].ToString();
byte[] img = (byte[])(reader[4]);
if (img == null)
pictureBox3.Image = null;
MemoryStream ms = new MemoryStream(img);
pictureBox3.Image = Image.FromStream(ms);
textBoxstudno.Text = "";
textBoxcourse.Text = "";
textBoxfname.Text = "";
textBoxlname.Text = "";
pictureBox3.Image = null;
MessageBox.Show("does not exist");
catch (Exception ex)


So to answer your question, your sql query has incorrect syntax. I would break point on the sql string to see exactly what's wrong. It should be obvious when you do that.

The REAL problem though is that you're exposing your application to SQL injection. Let's look at a basic example of what you have.

"SELECT * FROM table WHERE id ='" + userinput.Text + "'";

So the user inputs some value and it gets dumped in there for the query. Simple right?

What happens if the user inputs this

' OR 1==1; --

Well let's see what your sql string turns into when that's added

SELECT * FROM table WHERE id = '' OR 1=1; -- '

So now, your query string says select the id OR where 1=1 which means where true, which means everything.

SQL injection is a real threat and the only way to stop it is to implement counter measures right from the start.

Please look into parameterization. It's very easy in C#.

MSDN Article on C# Parameterization