Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to handle SQL statements with apostrophes in strings? 2

Status
Not open for further replies.

davidd31415

Programmer
Jan 25, 2006
154
US
I am creating records using SQL as follows:

Code:
Dim DB as DAO.Database
Set DB = CurrentDb
strSQL = "INSERT INTO Transactions (TextField) VALUES ('"  & textString & "')"
DB.Execute (strSQL)
DB.Close
Set DB = Nothing

If textString contains an apostrophe the SQL statement is corrupted. How do I stop this from happening while allowing apostrophes to be stored in TextField?

Thanks,

David
 
Use the Replace function to add a second apostrophe for each one it finds:

VALUES ('" & [red]Replace([/red]textString[red],"'","''")[/red] & "')"

 
VALUES (" & Chr(34) & textString & Chr(34) & ")"


HTH RuralGuy (RG for short) acXP winXP Pro
Please respond to this forum so all may benefit
 
RG, what happens if textString contains a double quote ?
 
Perfect.

Thanks for the quick replies- much appreciated.

David
 
PHV,
*Then* you have to resort to changing the textString but it is not my first choice. I resist changing users data as much as I can. For me it is always a last resort.

HTH RuralGuy (RG for short) acXP winXP Pro
Please respond to this forum so all may benefit
 
Double quotes do not work with the Chr(34) method, haven't tried the other yet.
 
I disagree, you haven't to change users data but use foolproof SQL syntax (ie doubling the delimiting quote inside the text as suggested by GhostWolf and posted by myself in many threads ...)
 
David: I knew double quotes would not work but you talked about the apostrophe.

PHV: I now agree that the Replace method will work all of the time in this situation and as such is a better solution here.

HTH RuralGuy (RG for short) acXP winXP Pro
Please respond to this forum so all may benefit
 
RuralGuy: I was just answering PHV's question.

I switched to the Replace() method since it seems to be the better way to go.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top