-1

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!

Nimantha
  • 6,405
  • 6
  • 28
  • 69
NPGuy
  • 11
  • 2

2 Answers2

0

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')
Nimantha
  • 6,405
  • 6
  • 28
  • 69
NPGuy
  • 11
  • 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 '.

bwdm
  • 793
  • 7
  • 17