This is the error message
MySql.Data.MySqlClient.MySqlException: ‘You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ””)’ at line 1′
this is my query
MySqlCommand cmd = new MySqlCommand("insert into subject(id, code, title, unit) values('" + textBox1.Text + "',''" + textBox2.Text + "',''" + textBox3.Text + "',''" + textBox4.Text + "')", conn);
I’ve been looking over at it for over an hour now and I still get this error.
Advertisement
Answer
It is recommended to use Parameterized Query.
UPDATED: As suggested by @CodeCaster for the concerns mentioned in Stop Using AddWithValue() article, I switch all the AddWithValue()
to Add("@Parameter", SqlDbType).Value
.
MySqlCommand cmd = new MySqlCommand("insert into subject(id, code, title, unit) values(@ID, @Code, @Title, @Unit)", conn); cmd.Parameters.Add("@ID", SqlDbType.int).Value = textBox1.Text; cmd.Parameters.Add("@Code", SqlDbType.Varchar, 10).Value = textBox2.Text; cmd.Parameters.Add("@Title", SqlDbType.NVarchar, 50).Value = textBox3.Text; cmd.Parameters.Add("@Unit", SqlDbType.Varchar).Value = textBox4.Text;
And also be sure that the value you pass with the SqlDbType
must match the data type as respective database table column.
The reasons to use Parameterized Query are:
- It simplifies the query in passing the parameters and makes the query become more readable.
- Prevent SQL Injection.
Reference: Prepare MySQL Statement