Parameterized Queries - MySQL
I come from a PHP background, where there is no such thing as parameterized queries. You simply build your own SQL string and make sure it doesn't contain anything harmful.
So, not having heard of such thing as parameterized queries, I created my SQL statements the same way in C#, until I read about this practice being "not done". So, I wanted to fix it.
I'm using MySQL with the MyODBC driver. But MySQL is tricky, it doesn't support named parameters, so you have to use a question mark and add parameters in the right order.
No problem I thought, this would be a one-minute fix.
This is what I had (I returned an SQL query string at first):
1return String.Format("INSERT INTO zosa_Users(UserVNaam, UserNaam, UserKlasNr, UserKlas) VALUES('{0}', '{1}', {2}, {3});", strFName, strGeslacht, intKlas, klKlas.Id);
And I changed it to: 1OdbcCommand insertCmd = new OdbcCommand("INSERT INTO zosa_Users(UserVNaam, UserNaam, UserKlasNr, UserKlas) VALUES('?', '?', ?, ?);", zosaDb);What did this insert in my database? Well it added a question mark ;)
2insertCmd.Parameters.Add(new OdbcParameter("", strFName));
3insertCmd.Parameters.Add(new OdbcParameter("", strGeslacht));
4insertCmd.Parameters.Add(new OdbcParameter("", intKlas));
5insertCmd.Parameters.Add(new OdbcParameter("", klKlas.Id));
6return insertCmd;
So, I went looking for what was wrong... Did I add my parameters in a wrong way? Is there something wrong with MyODBC? After having done about everything I could think of, it was in the middle of the night and I went to bed. But today I tried something else, remove the single quotes. And it worked!
1OdbcCommand insertCmd = new OdbcCommand("INSERT INTO zosa_Users(UserVNaam, UserNaam, UserKlasNr, UserKlas) VALUES(?, ?, ?, ?);", zosaDb);Such a small thing, but nowhere I managed to find this, nobody ever posted to watch out for this. Having no previous experiences with parameters and the question mark, I simply thought it would safely replace the ? with my value, but still would require the quotes for string values.
2insertCmd.Parameters.Add(new OdbcParameter("", strFName));
3insertCmd.Parameters.Add(new OdbcParameter("", strGeslacht));
4insertCmd.Parameters.Add(new OdbcParameter("", intKlas));
5insertCmd.Parameters.Add(new OdbcParameter("", klKlas.Id));
6return insertCmd;
Don't make the same mistake! It's a stupid one ;)