简体   繁体   English

如何使用Python将CSV字符串加载到MySQL中

[英]How to load a CSV string into MySQL using Python

In my use case, I have a csv stored as a string and I want to load it into a MySQL table. 在我的用例中,我将csv存储为字符串,并且想要将其加载到MySQL表中。 Is there a better way than saving the string as a file, use LOAD DATA INFILE, and then deleting the file? 是否有比将字符串另存为文件,使用LOAD DATA INFILE然后删除文件更好的方法? I find this answer but it's for JDBC and I haven't find a Python equivalent to it. 我找到了这个答案,但是它是针对JDBC的,而我还没有找到与之等效的Python。

Yes what you describe is very possible! 是的,您所描述的可能性很大! Say, for example, that your csv file has three columns: 举例来说,您的csv文件包含三列:

import MySQLdb
conn = MySQLdb.connect('your_connection_string')
cur = conn.cursor()
with open('yourfile.csv','rb') as fin:
    for row in fin:
        cur.execute('insert into yourtable (col1,col2,col3) values (%s,%s,%s)',row)
cur.close(); conn.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM