How can I escape apostrophes in my SQL statement? [duplicate] - sql

This question already has answers here:
ColdFusion adding extra quotes when constructing database queries in strings
(4 answers)
Closed 7 years ago.
Not to get into a discussion about SQL injection and sanitizing and etc...
For various reasons, I am doing the unspeakable and building and executing a dynamic SQL query WITHOUT using query params.
So... I'm building a list of columns and a list of values, and then I have the following code:
insertRecord.setSql("INSERT INTO MyTable(" & columns & ") VALUES(" & values & ")");
This works properly for most records, but for a few records one of the string field values has an apostrophe or single quote:
'SHERIFF'S OFFICE'
This is giving me the SQL error: Incorrect syntax near 'S'.
I have tried using preserve single quotes in several ways and it doesn't help:
insertRecord.setSql("INSERT INTO MyTable(" & columns & ") VALUES(" & preserveSingleQuotes(values) & ")");
OR
insertRecord.setSql(PreserveSingleQuotes("INSERT INTO MyTable(" & columns & ") VALUES(" & values & ")"));
Is there any way to escape all the apostrophes, or otherwise format my sql string properly, other than using a ReplaceNoCase(colValue, "'", "''") on each value individually as I'm building the string (which does work)?

I'm not sure of the syntax for the setSql statement but perhaps you are missing single quotes around your string values. Have you tried adding those?
What I mean is this. Assuming the SQL statement needs to look something like this (notice the quotes around each value):
INSERT INTO MyTable
(column1, column2, column3)
VALUES
('value 1', 'value 2', 'value 3')
Then the setSql statement should look like:
insertRecord.setSql("INSERT INTO MyTable (column1, column2, column3) VALUES ('value 1', 'value 2', 'value 3')");
So you could try something like (notice the single quotes around the values):
insertRecord.setSql("INSERT INTO MyTable(" & columns & ") VALUES('" & preserveSingleQuotes(values) & "')");
You might also need to loop over every values in order to enclose each within the single quotes.

Related

How do I use a comma delimited string as query criteria on a numeric field

I've built a function that creates a comma delimited string from multiple selections in my list box. When I try to use this as the Where clause in my sql (in VBA) I get a 'type mismatch' error - because the field I'm using with the criteria is numeric. How do I resolve this?
example:
sql = "INSERT INTO tblItemsLibrary ( Constr, Description) ...
"WHERE (((tblItemsLibrary1.ItemsLibID) In (" & strSelectedRecords & ")));"
In the above example strSelectedRecords is coming in as "17,11,28" where the field is a long.
You can use LIKE:
INSERT INTO tblItemsLibrary ( Constr, Description)
...
WHERE "," & tblItemsLibrary1.ItemsLibID) & "," LIKE "*," & strSelectedRecords & ",*"
Actually you might want to adjust strSelectedRecords to start and end with *, and ,*.
If you are using SQL Server 2016 or above, the function string_split can be used:
SELECT *
FROM tblItemsLibrary
WHERE tblItemsLibrary1.ItemsLibID IN (select * from STRING_SPLIT(#numlist, ','))
Replace #numlist with your string 17,11,28
Another method is to construct dynamic sql and pass that on top of base sql statement:
EXECUTE('SELECT * FROM tblItemsLibrary1 WHERE ItemsLibID IN
('+#numlist+')')
Your SQL expression will result in:
INSERT INTO tblItemsLibrary ( Constr, Description)
...
WHERE (((tblItemsLibrary1.ItemsLibID) In (17,11,28)));
which is correct if ItemsLibID is numeric.
Thus, your error is probably caused by the values you try to insert.

Dot separated value is inserted instead of comma in asp

I'm kinda "fresh" in classic ASP and I have the following insert SQL query in classic ASP and i can't make it insert comma separated value from a CSV file in MS Access database, but instead it will convert it in dot separated thousand value.
E.g.:
price = "49,55"
insert_sql = "INSERT INTO table (price) VALUES ('" & price & "')
DataConn.execute(insert_sql)
I tried to convert it like:
CDbl(price) or FormatNumber(price)
but what i get after all is 4.955,00.
I've tried changing localization, but i still have the same problem.
P.S.: I am aware of the fact that the above code is SQL Injection vulnerable, but for now i'm trying to understand what's wrong, or what do i forget.
Thanks.
Use Str to force a dot as the decimal separator:
insert_sql = "INSERT INTO table (price) VALUES (" & Str(price) & ")"
Then, for display of the price, apply any format you prefer.

MS Access / SQL : error in insert query statement

I am using MS Access 1997 version (.mdb file). On a daily basis, I need to insert values manually. In that file, there's a column Logical (Boolean data type). I am automate this template using SQL query instead of direct entry.
Below is my insert query:
Insert Into Data_CustomerTransmit_Tbl (Logical)
Values (" & Logicalnme & ")
Values:
Logicalnme - True
When I run this query in VBA in Excel, I get this error message
Syntax Error in Insert into Statement
Kindly confirm shall I use "Logical" as column name or this is the reserved keyword?
Thanks in advance.
There isn't a problem with your field name, you just need to enclose your INSERT column name in square brackets. You also need to choose a valid value in the VALUES clause:
INSERT INTO Data_CustomerTransmit_Tbl ( [Logical] )
VALUES (TRUE);
If you want to be prompted for the value to insert, you can use a parameter:
PARAMETERS [Please enter a Boolean value] YesNo;
INSERT INTO Data_CustomerTransmit_Tbl ( [Logical] )
VALUES ([Please enter a Boolean value]);
I presume you are trying to do this insert using VBA? If so, your syntax in building the SQL statement is correct, except you have some punctuation missing: double-quotes on each end.
"INSERT INTO Data_CustomerTransmit_Tbl (Logical) VALUES (" & Logicalnme & ")"
Further, as you have split the string over two lines (breaking before VALUES), you must also terminate the first line of the string with: ' " & _' (space,double-quote,space, ampersand, space, underscore) in order to indicate that the string continues to the next line. Then you begin the next line with double-quotes:
"INSERT INTO Data_CustomerTransmit_Tbl (Logical) " & _
"VALUES (" & Logicalnme & ")"
In VBA the code should look like this:
Docmd.RunSQL("INSERT INTO Data_CustomerTransmit_Tbl (Logical) VALUES (" & Logicalnme & ");"
The SQL query you alluded to - have you tried to execute it manually in the query editor using the same value(s) you are trying to pass from Excel? That would immediately provide more verbose feedback if there is an issue with the query or the data.
Regarding the Boolean field, make sure you are receiving a True/False that you are expecting, not a bit field, 0 and 1. I like to make quick log entries in a table or a file when troubleshooting to see the raw data.
Use Cbool function:
Insert Into Data_CustomerTransmit_Tbl (Logical)
Values (" & Cbool(Logicalnme) & ")
Add single quotes around values?
sql = "INSERT INTO Data_CustomerTransmit_Tbl (Logical) " & _
"VALUES ('" & Logicalnme & "')"
docmd.runsql sql

Loading Chinese character to DB2 using SQL Insert statement

I need to use VBA excel macro to load Chinese character data from excel spreadsheet to DB2 using SQL Insert Statement. I know that this cannot work with normal Insert statement as below:
INSERT INTO table_name
VALUES (value1,value2,value3,...);
Since this is my first time dealing with double byte character, can anybody help to guide me on which method I can use to load DBCS data into DB2.
Thanks in advance.
A few things:
Not knowing your table and column names, enclose them with square brackets to be on the safe side
There must be no space between the N' prefix and the Unicode data, nor a space after the value itself
Your data1 value is not enclosed in quotation marks; this means it must be a numeric value. If it is not a numeric value, enclose it in quotation marks. If it is a Unicode string, enclose it in "N'..."'"
Try with this:
oStr = "INSERT INTO [" & tableName & "] ([" & field1 & "], [" & field2 & "]) Values(" & data1 "," & " N'" & data2 & "');"

VB String Concatenation Incomplete

I met a strange problem. I wanted to add string and string but it did not add together in actual.
Below is my code:
sql = "insert into Table (a,b,c,d) values ('" + a.value + "',b,'" + c.value + "',0)"
I use MessageBox to show this string and it just shows
insert into Table (a,b,c,d) values ('a
How can I modify it?
Always use an ampersand "&" when appending strings in VB.NET.
Change the code to
sql = "insert into Table (a,b,c,d) values ('" & a.value & "',b,'" & c.value & "',0)"
you ca use + as below
sql = "insert into Table (a,b,c,d) values ('" + a.value.ToString() + "',b,'" + c.value.ToString() + "',0)"
you need to convert the values to string if they are already not strings
but here you specify ,b, without '', if it is string then you need to add that as below
sql = "insert into Table (a,b,c,d) values ('" + a.value.ToString() + "','b','" + c.value.ToString() + "',0)"
if you using & operator then you don't need to convert to strings. read more about this check this link.
all above for string Concatenation but regarding SQL statement I would recommend you to use parameterized SQL statement.
How do I create a parameterized SQL query? Why Should I?