I am attempting to generate an INSERT statement into an SQL Server database from a Data Frame:
data_frame.to_sql(table, engine, if_exists='append', index=False)
The Data Frame is created from a JSON Response.
I am having issues inserting String values with single quotes in them into the database. The reason appears to be that the Data Frame fields are double quoted if there is a single quote anywhere in the field. Example of the behavior:
INSERT INTO my_table(column1, column2, column3) VALUES ('value1', "value2's", 'value3');
Because value2's has a single quote in it, .to_sql() surrounds the field with double quotes instead. However, SQL Server believes this value to be a column instead because it's double quoted and the insert fails.
How can I get .to_sql()
to instead format the INSERT statement like below:
INSERT INTO my_table(column1, column2, column3) VALUES ('value1', 'value2''s', 'value3');
The Error message .to_sql()
generates:
The identifier that starts with 'value2's' is too long. Maximum length is 128.
The error message above suggests that the database is treating the Data Frame value as a column name. SQL Server often gives this error if a value is double quoted instead of single quoted.
Libraries (some may not be relevant to this issue):
import pyodbc
import sqlalchemy
from sqlalchemy import MetaData
import pandas as pd
from sqlalchemy.engine import URL
Any help is appreciated!