{已解决}在MySQL/Python中创建带有转义字符的插入查询

2024-10-01 22:33:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个脚本,将数据从Access数据库传输到MySQL数据库。我正在尝试生成一个类似于以下内容的查询:

INSERT into customers (firstname, lastname) value ('Charlie', "D'Amelio");

然而,MySQL不喜欢上面列出的双引号。我编写了一个笨拙的函数,试图用a替换“in D'Amelio”。下面是创建SQL语句的整个函数:

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

目前,它只是完全忽略了这个值。关于替换什么或如何改进功能的任何提示?谢谢大家!


Tags: key函数in数据库fieldsstringmysqldict
2条回答

您可以调用Python的replace。终端中的示例:

>>> s = "D'Amelio"
>>> s.replace("'", "'")
"D'Amelio"

在本例中,第一个参数是单引号,第二个参数是锐重音

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')

这个修好了,谢谢大家的帮助

相关问题 更多 >

    热门问题