Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a button that executes this sql query:

C#
sqlcmdInsertPhysicalNote.CommandText = "INSERT INTO DriverPhysicalNotes
(DriverInformationID, PhysicalNoteDate, PhysicalNote) VALUES ('" +
ddlDriverName.SelectedValue + "','" + DateTime.Now.ToShortDateString() +
"','" + txtNotes.Text + "')";



I am having a problem when a user enters an string between apostrophe e.g 'string' into the textbox it cause the error. THis is the error

SQL
Incorrect syntax near 'string'.


How can I keep this from happening? Quotes in the notes section should be
allowed.

Thanks,
Posted
Updated 17-Mar-14 21:31pm
v2

can you please try to modified your code like this...

C#
sqlcmdInsertPhysicalNote.CommandText = "INSERT INTO DriverPhysicalNotes
(DriverInformationID, PhysicalNoteDate, PhysicalNote) VALUES ('" +
ddlDriverName.SelectedValue + "','" + DateTime.Now.ToShortDateString() +
"','" + txtNotes.Text.Replace("'","''") + "')";


One more thing, always be sure that, when you are giving user a text box which is accepting any string value like Memo, Notes, Description etc.. or anything at that time always tack care for ' (quot) you always need to replace it with '' (double quot).
 
Share this answer
 
v2
Comments
Tejas Vaishnav 18-Mar-14 3:25am    
if it will be solve your problem, please accept my solution as answer and also don't forget to rate it.
Harpreet_125 18-Mar-14 3:33am    
i have updated my question.. please go through my question and answer me again..
Simple: don't do it like that!
The reason it's a problem is that you are concatenating strings to form your SQL command - which is very dangerous as it allows SQL Injection attacks as well as causes syntax errors!
Use a parametrised query instead:
C#
sqlcmdInsertPhysicalNote.CommandText = "INSERT INTO DriverPhysicalNotes
(DriverInformationID, PhysicalNoteDate, PhysicalNote) VALUES (
@DM, @DT, @NT)";
sqlcmdInsertPhysicalNote.InsertCommand.Parameters.AddWithValue("@DM", ddlDriverName.SelectedValue);
sqlcmdInsertPhysicalNote.InsertCommand.Parameters.AddWithValue("@DT", DateTime.Now);
sqlcmdInsertPhysicalNote.InsertCommand.Parameters.AddWithValue("@NT", txtNotes.Text);
 
Share this answer
 
Comments
Harpreet_125 18-Mar-14 3:33am    
i have updated my question.. please go through my question and answer me again..
Harpreet_125 18-Mar-14 3:41am    
thanks.. this is working for me...
OriginalGriff 18-Mar-14 5:35am    
You're welcome!
this type of cases always use parameters.............then working fine...........
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900