By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,967 Members | 1,178 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,967 IT Pros & Developers. It's quick & easy.

insert into syntax error while using a variable containing quotes

P: 1
I an adding data into an access table via c# and have run into a roadblock. The syntax is

Expand|Select|Wrap|Line Numbers
  1. addSQL = "INSERT INTO history ([id], [partner], [from], [msgdate], [msgtime], [message]) VALUES ('" + thisid + "','" + chat.DialogPartner + "','" + chatmessage.FromHandle + "','" + chatmessage.Timestamp.Date + "','" + chatmessage.Timestamp.TimeOfDay + "','" + chatmessage.Body + "')";
The problem relates to the last item, chatmessage.Body, which can contain anything a person can type, including single and double quotes. So how do I get the contents of that variable inserted into an access table?
Nov 6 '11 #1
Share this Question
Share on Google+
3 Replies


Rabbit
Expert Mod 10K+
P: 12,421
Escape the quotes before appending them to the string.
Nov 7 '11 #2

100+
P: 759
...or double any quote in chatmessage.Body
If chatmessage.Body is abcd"efgh"ijc then transform this in abcd""efgh""ijc.
Nov 7 '11 #3

NeoPa
Expert Mod 15k+
P: 31,709
Try :
Expand|Select|Wrap|Line Numbers
  1. string strBody;
  2. strBody = (string)chatmessage.Body
  3. strBody = strBody.Replace("'", "''");
  4. addSQL = "INSERT INTO history " +
  5.          "([id], [partner], [from], [msgdate], [msgtime], [message]) " +
  6.          "VALUES ('" + thisid + "','" + chat.DialogPartner + "','" + 
  7.          chatmessage.FromHandle + "','" + chatmessage.Timestamp.Date + 
  8.          "','" + chatmessage.Timestamp.TimeOfDay + "','" + strBody + "')";
PS. If I got some of the syntax wrong then I'm sure you can fix it. I've not done too much C# code.
Nov 12 '11 #4

Post your reply

Sign in to post your reply or Sign up for a free account.