【问题标题】:{SOLVED} Creating an insert query with escape characters in MySQL/Python{已解决} 在 MySQL/Python 中使用转义字符创建插入查询
【发布时间】:2021-10-30 08:40:32
【问题描述】:

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

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

然而,MySQL 不喜欢上面列出的双引号。我编写了一个笨重的函数来尝试用 ' 替换 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

目前它只是完全忽略了该值。关于用什么替换 ' 或如何改进我的功能的任何提示?谢谢!

【问题讨论】:

  • 使用带参数的prepared statement,就不用担心转义了。
  • 您必须在值中使用双引号 char。 INSERT into customers (firstname, lastname) value ('Charlie', 'D''Amelio');
  • 没有@Akina 最好使用准备好的语句
  • @nbk 关于用什么替换 ' 的任何提示 - 双引号字符。 或如何改进我的功能? - 使用准备好的语句。
  • 使用this Q&A中描述的技术

标签: python mysql sql mysql-python mysql-connector


【解决方案1】:

你可以只调用 Python 的替换。终端中的示例:

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

在这种情况下,第一个参数是单引号 ',第二个参数是重音符号 '。

【讨论】:

    【解决方案2】:
    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')
    

    已经解决了,谢谢大家的帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-25
      相关资源
      最近更新 更多