将 Python 字典 (dict) 对象转储到 MySQL 表的最快方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2611239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 01:04:00  来源:igfitidea点击:

Quickest way to dump Python dictionary (dict) object to a MySQL table?

pythonmysqldictionary

提问by ThinkCode

I have a dict object. I dumped the data using this:

我有一个 dict 对象。我用这个转储了数据:

for alldata in data: # print all data to screen
    print data[alldata]

Each field had brackets [] and 'None' values for NULLS and date.datetime for date values.

每个字段都有方括号 [] 和 'None' 值用于 NULLS 和 date.datetime 用于日期值。

How do I dump this dict to MySQL table? Thank you!

如何将此 dict 转储到 MySQL 表?谢谢!

print data displays something like this :

打印数据显示如下:

{'1': ['1', 'K', abc, 'xyz', None, None, None], '2': ['2', 'K', efg, 'xyz', None, None, None], '3': ['3', 'K', ijk, 'xyz', None, None, None]}

How to insert this data into MySQL?

如何将这些数据插入到 MySQL 中?

回答by newtover

Assuming you have MySQLdb(mysql-python) installed:

假设您安装了MySQLdb(mysql-python):

sql = "INSERT INTO mytable (a,b,c) VALUES (%(qwe)s, %(asd)s, %(zxc)s);"
data = {'qwe':1, 'asd':2, 'zxc':None}

conn = MySQLdb.connect(**params)

cursor = conn.cursor()
cursor.execute(sql, data)
cursor.close()

conn.close()

回答by Azamat Tokhtaev

回答by kilokahn

This is a possible duplicate of, or can be answered by this post Using a Python dict for a SQL INSERT statement

这是一个可能的重复,或者可以通过这篇文章使用 Python 字典来回答 SQL INSERT 语句

However, to answer your question, I posted this over on the other question and i'm reposting it here as well:

但是,为了回答您的问题,我将其发布在另一个问题上,并且我也在此处重新发布:

def ins_query_maker(tablename, rowdict):
keys = tuple(rowdict)
dictsize = len(rowdict)
sql = ''
for i in range(dictsize) :
    if(type(rowdict[keys[i]]).__name__ == 'str'):
        sql += '\'' + str(rowdict[keys[i]]) + '\''
    else:
        sql += str(rowdict[keys[i]])
    if(i< dictsize-1):
        sql += ', '
query = "insert into " + str(tablename) + " " + str(keys) + " values (" + sql + ")"
print(query) # for demo purposes we do this
return(query) #in real code we do this

For a dictionary

对于字典

tab = {'idnumber': 1, 'fname': 'some', 'lname': 'dude', 'dob': '15/08/1947', 'mobile': 5550000914, 'age' : 70.4}

we get the output as the screenshot below shows. Note this is a bare-bones example and needs sanity checks, and can be modified for bulk updates (using a dict of dicts), etc.

我们得到如下图所示的输出。请注意,这是一个简单的示例,需要进行完整性检查,并且可以针对批量更新进行修改(使用 dict 的 dict)等。

output of the code mentioned above

上面提到的代码的输出