A very common error which can occur when doing an insert into a database if you are using plain SQL statements instead of a stored procedure is when you don't take care of the common SQL injection mistakes..(SQL injection is a very huge topic and there are so many expert advice online which i am not going to discuss here).
Coming to the post, to avoid the error of sql statements when inserting records, The most common way of getting sql insert or update error is , when you write a query like the one below.
"Insert into UserDetails(UserName,Password) Values( ' " + txtUserName.Text + " ' ,' " + txtPassword.Text + " ' ) " ;
We have no control over what the user enters, Of course there are validators and we can keep a good check there..what if we missed certain conditions? What if the user enters in the provided textbox a value like this " I'll be there" or "C'mon guys"...basically any extra single quote that is not supposed be there...To avoid this error, one way is
txtUserName.Text.Replace(" ' "," ' ' ")
[Note: here any single quote is replaced with 2 single quotes and not a single double quote]
This will take care of any single quote errors. Of course,as told earlier there are other SQL injection problems, but this is one less error to take care of...
One other good way i have seen is have a class called RemoveBadChars which will be called first to kill unnecessary characters and then pass the variables to the stored proc or the insert statement...
Any other good practices,please leave a comment
Happy Coding :)
Saturday, February 17, 2007
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment