【问题标题】:Use a python dictionary to insert into mysql使用python字典插入mysql
【发布时间】:2016-01-25 00:48:39
【问题描述】:

我正在尝试从字典中获取数据(该示例为便于阅读而进行了简化)并将其插入到 mysql 数据库中。 我有以下代码。

import pymysql 
conn = pymysql.connect(server, user , password, "db")
    cur = conn.cursor()
    ORFs={'E7': '562', 'E6': '83', 'E1': '865', 'E2': '2756 '}
    table="genome"
    cols = ORFs.keys()
    vals = ORFs.values()
    sql = "INSERT INTO %s (%s) VALUES(%s)" % (
    table, ",".join(cols), ",".join(vals))

    print sql
    print ORFs.values()
    cur.execute(sql, ORFs.values())


    cur.close()
    conn.close()

print sql 语句返回
INSERT INTO genome (E7,E6,E1,E2) VALUES(562,83,865,2756 )
当我直接在 mysql 命令行中输入它时, mysql 命令有效。但是当我运行 python 脚本时出现错误:

<type 'exceptions.TypeError'>: not all arguments converted during string formatting
      args = ('not all arguments converted during string formatting',)
      message = 'not all arguments converted during string formatting' 

一如既往,我们将不胜感激任何建议。

【问题讨论】:

    标签: python mysql dictionary pymysql


    【解决方案1】:

    上一个答案不适用于非字符串字典值。这是修订版。

        format_string = ','.join(['%s'] * len(dict))
        self.db.set("""INSERT IGNORE INTO listings ({0}) VALUES ({1})""".format(", ".join(dict.keys()),format_string), 
                             (dict.values()))
    

    【讨论】:

    • 3.7 之前的 Python 版本不保证保留字典插入顺序。 3.6 版执行此操作,但仅从 3.7 版开始,这是规范的一部分。
    【解决方案2】:
    sql = "INSERT INTO %s (%s) VALUES(%s)" % (
        table, ",".join(cols), ",".join(vals))
    

    此 SQL 包含值,cur.execute(sql, ORFs.values()) 也包含值。

    所以,应该是cur.execute(sql)。

    【讨论】:

    • 非str值时会出问题
    【解决方案3】:

    就我而言,我将跳过空列。

    data = {'k': 'v'}
    fs = ','.join(list(map(lambda x: '`' + x + '`', [*data.keys()])))
    vs = ','.join(list(map(lambda x: '%(' + x + ')s', [*data.keys()])))
    sql = "INSERT INTO `%s` (%s) VALUES (%s)" % (table, fs, vs)
    count = cursor.execute(sql, data)
    

    【讨论】:

      猜你喜欢
      • 2015-06-10
      • 1970-01-01
      • 2020-03-04
      • 2013-08-17
      • 1970-01-01
      • 2022-10-18
      • 2011-02-07
      • 2021-07-19
      • 2022-01-21
      相关资源
      最近更新 更多