'Creating an insert query with escape characters in MySQL/Python
I am writing a script that transfers data from an Access database to a MySQL database. I'm am trying to generate a query similar to below:
INSERT into customers (firstname, lastname) value ('Charlie', "D'Amelio");
However, MySQL does not like double quotes like those listed above. I wrote a clunky function to try to replace the ' in D'Amelio with a '. Here is the whole function to create the SQL statement below:
def dictionary_output(dict):
output = "INSERT into lefm_customers "
fields = "(id, "
vl = "('" + id_gen() + "', "
for key in dict.keys():
# print(dict[key])
if str(dict[key]) == 'None' or str(dict[key]) == "":
pass
elif "'" in str(dict[key]):
fields = fields + str(key) + ", "
string = ""
for character in string:
if character == "'":
string += r"\'"
else:
string += character
vl = "'" + string + "', "
else:
fields = fields + str(key) + ", "
vl = vl + "'" + str(dict[key]) + "', "
fields = fields[:-2] + ")"
vl = vl[:-2] + ");"
return "INSERT into lefm_customers " + fields + " values " + vl
Currently it is just ignoring that value altogether. Any tips on what to replace ' with or how I can improve my function? Thank you!
Solution 1:[1]
This fixed it:
def dictionary_output(dict):
lst = []
output = "INSERT into lefm_customers "
fields = "(id, "
vl = "('" + id_gen() + "', "
for key in dict.keys():
# print(dict[key])
if str(dict[key]) == 'None' or str(dict[key]) == "":
pass
else:
fields = fields + str(key) + ", "
vl = vl + "%s, "
lst.append(dict[key])
fields = fields[:-2] + ")"
vl = vl[:-2] + ");"
return ("INSERT into lefm_customers " + fields + " values " + vl, lst)
for name in access_dict:
if str(name) not in mysql_dict.keys():
try:
statement = dictionary_output(access_dict[name])
mysql_cursor.execute(statement[0], statement[1])
print('attempting ' + str(name))
db_connection.commit()
print("Success!")
except:
print('something went wrong')
Solution 2:[2]
You can just call Python's replace. Example in the terminal:
>>> s = "D'Amelio"
>>> s.replace("'", "'")
"D'Amelio"
In this case the first argument is the single quote ' and the second is the acute accent '.
Solution 3:[3]
This question is not what Stack Overflow is for - it's for fixing code. You provide the code, we try to fix it. But, anyway -
In our company we use OBS for recording video. It is free, and is advertised as working under Windows, MacOS and Linux - I can say that it works well under Windows. https://obsproject.com/
I hope this is useful.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nimantha |
| Solution 2 | bwdm |
| Solution 3 | Francis King |
