With a script in Python3
, after extracting some strings from a file, they should be used as data to be inserted into a MySQL database as follows:
query1 = """INSERT INTO {:s} VALUES ({:s}, {:s}, {:s}, {:s});""".format(table1,"""0""",string1,string2,string3)
cursor1.execute(query1)
Some of the strings contain different and unpleasant quotes, like:
a "'double quoted'" example string
If I define some example strings with triple quotes delimiters
string1 = """a "'double quoted'" example string"""
the above query is successful. If instead the strings are returned by a function after parsing an external file, the query generates an error:
_mysql_exceptions.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'first string, "\'Quoted part\'" of second string, , Third string\' at line 1')
I tried also with:
query1 = """INSERT INTO {:s} VALUES ('{:s}', '{:s}', '{:s}', '{:s}');""".format(table1,"""0""",string1,string2,string3)
but the same error is generated.
Also
query1 = """INSERT INTO %s VALUES (%s, %s, %s, %s);"""
data1 = ("""table1"""","""0""",string1,string2,string3)
cursor1.execute(query1,data1)
and
query1 = """INSERT INTO %s VALUES ('%s', '%s', '%s', '%s');"""
data1 = ("""table1"""","""0""",string1,string2,string3)
cursor1.execute(query1,data1)
generate the same error.
How to fix this? Maybe, once the strings have been returned by the function, is it possible to re-define them with triple quotes?