Results 1 to 5 of 5

Thread: Single Quotes in SQL String

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Sep 2001
    Posts
    25

    Single Quotes in SQL String

    How do I code my program so that if a user enters a single quote in a string value that I have to pass as a SQL statement, there will be no ODBC error.

    like "David's" ... it come back with an odbc invalid format error.


    Thanks

  2. #2
    Hyperactive Member MetallicaD's Avatar
    Join Date
    Feb 2001
    Location
    Tallahassee, FL
    Posts
    488
    You need to run that string through the wringer.. create a small function that you can pass a string into with a boolean that determines if you want to encode for SQL or decode for text... then in that function, use the Replace function and replace any ' with something like &sq.. or reverse, replace &sq with ' on the way out


    VB Code:
    1. Public Function SQLStringConv(str as String, bolInOut as Boolean) as String
    2. If bolInOut Then
    3.    SQLStringConv = Replace(str, "'", "&sq")
    4. Else
    5.    SQLStringConv = Replace(str, "&sq", "'")
    6. End If
    7.  
    8. End Function

    -mcd
    [vbcode]
    '*****************************
    MsgBox "MCD :: [email protected]", vbInformation + vbOKOnly, "User"
    '*****************************
    [/vbcode]

  3. #3
    Addicted Member JasonGS's Avatar
    Join Date
    May 2000
    Location
    California
    Posts
    155
    You can also double the character to 'escape' it. This function works pretty good for me anyways...

    Code:
    Function Fix39(ByVal Text As String) As String
    
        Fix39 = Replace(Text, Chr(39), Chr(39) & Chr(39))
    
    End Function

  4. #4
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373
    pretty much the same thing.. but i made a function in a module

    Code:
    Public Function Apost(sString as string)
        Apost = Replace("'","''")
    End Function
    then when you make your SQL statment... i would use

    Code:
    sSql = "INSERT INTO tblTable [MyField] Values('" & apost(txtName) & "')"

  5. #5
    DerFarm
    Guest
    It reads a LOT better if you use chr$(34) instead of doubling the
    quotes.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width