Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将Python字典中的数据插入MySQL?_Python_Mysql_Dictionary - Fatal编程技术网

如何将Python字典中的数据插入MySQL?

如何将Python字典中的数据插入MySQL?,python,mysql,dictionary,Python,Mysql,Dictionary,我处理了MySQL中的一些数据,结果字典“data”(打印数据)显示如下: {'1': ['1', 'K', abc, 'xyz', None, None, None, datetime.date(2009, 6, 18)], '2': ['2', 'K', efg, 'xyz', None, None, None, None], '3': ['3', 'K', ijk, 'xyz', None, None, None, datetime.date(2010, 2, 5, 16, 31, 2

我处理了MySQL中的一些数据,结果字典“data”(打印数据)显示如下:

{'1': ['1', 'K', abc, 'xyz', None, None, None, datetime.date(2009, 6, 18)],
 '2': ['2', 'K', efg, 'xyz', None, None, None, None],
 '3': ['3', 'K', ijk, 'xyz', None, None, None, datetime.date(2010, 2, 5, 16, 31, 2)]}

如何创建一个表并在MySQL表中插入这些值?换句话说,如何将它们转储到MySQL或CSV?不确定如何处理datetime.date和None值。非常感谢您的帮助。

datetime.date
匹配
date
字段,并且
None
变为
NULL
。结合使用以执行插入。

大多数兼容dbapi的MySQL连接器将自动将Python的
None
转换为SQL的
NULL
,将Python的
datetime
对象转换为SQL
时间戳
s


实际上,您只需要打开一个到数据库的连接,获取一个游标,然后在字典上迭代执行插入操作。如果不了解您的模式,就不可能给出示例代码。

下面是一些创建MySQL数据库和插入数据的基本代码

import MySQLdb
import datetime

THEHOST="localhost"
THEUSER="user"
THEPASSWD="passwd"
THEDB="database"

connection=MySQLdb.connect(
    host=THEHOST,user=THEUSER,passwd=THEPASSWD,db=THEDB)
cursor=connection.cursor()

abc,efg,ijk=1,2,3

data={'1': ['1', 'K', abc, 'xyz', None, None, None, datetime.date(2009, 6, 18)],
      '2': ['2', 'K', efg, 'xyz', None, None, None, None],
      '3': ['3', 'K', ijk, 'xyz', None, None, None,
            datetime.datetime(2010, 2, 5, 16, 31, 2)]}

sql='''\
CREATE TABLE IF NOT EXISTS temp (id int auto_increment primary key,
    field1 varchar(8),
    field2 int,
    field3 varchar(8),
    field4 bool,
    field5 varchar(8),
    field6 varchar(8),
    field7 datetime )'''

cursor.execute(sql)

sql='''\
INSERT INTO temp (id, field1, field2, field3, field4, field5, field6, field7)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
'''
cursor.executemany(sql, data.values())

您是否缺少一个
?(使用类…)是的,更新了!谢谢这只是样本数据。谢谢Ken。谢谢你的解决方案:)我一直遇到这个错误:TypeError:不是所有的参数都在字符串格式化过程中被转换。我使用了以下命令:sql=''\INSERT-INTO delUseThisTable(
key
primary
)值(%s,%s)''游标。EXECUTEMY(sql,data.VALUES())我在该表中有78列。我尝试了两列作为开始,但失败了。思想?谢谢你@NJTechie:也许可以尝试
打印数据.values()
。它应该是一个由两个元素组成的列表,例如
[[1,'K'],[2,'L']]
。内部列表必须正好有2个元素。否则,您可能会得到错误
TypeError:not all arguments converted…
OMG,sir您是个天才:)我不知道我们必须一次插入所有参数,而不是只插入两列!肯定学到了一两件事!非常感谢你!