insert into syntax error while using a variable containing quotes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Grant Andrews
    New Member
    • Nov 2011
    • 1

    #1

    insert into syntax error while using a variable containing quotes

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

    Code:
    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.Bod y, 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?
    Last edited by NeoPa; Nov 11 '11, 11:53 PM. Reason: Added mandatory [CODE] tags for you
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Escape the quotes before appending them to the string.

    Comment

    • Mihail
      Contributor
      • Apr 2011
      • 759

      #3
      ...or double any quote in chatmessage.Bod y
      If chatmessage.Bod y is abcd"efgh"ijc then transform this in abcd""efgh""ijc.

      Comment

      • NeoPa
        Recognized Expert Moderator MVP
        • Oct 2006
        • 32669

        #4
        Try :
        Code:
        string strBody;
        strBody = (string)chatmessage.Body
        strBody = strBody.Replace("'", "''");
        addSQL = "INSERT INTO history " +
                 "([id], [partner], [from], [msgdate], [msgtime], [message]) " +
                 "VALUES ('" + thisid + "','" + chat.DialogPartner + "','" + 
                 chatmessage.FromHandle + "','" + chatmessage.Timestamp.Date + 
                 "','" + 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.

        Comment

        Working...