在不使用load data命令的情况下填充数据库 [英] Populating a database without the load data command

查看:99
本文介绍了在不使用load data命令的情况下填充数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用load data命令的情况下将数据(.csv个文件)填充到MySql(Windows 5.1)中?

How do I populate data (.csv files) into MySql (Windows 5.1) without using the load data command?

推荐答案

他们是在试图让您学习脚本语言吗?
如果是这样,那么Python ...

Are they trying to get you to learn a scripting language?
If so, how about Python...

我刚刚测试了以下代码是否满足您的要求.
请注意:您需要下载第三方MySQLdb模块.

I just tested that the following code does what you require.
Please note: You'll need to download the 3rd-party MySQLdb module.

import csv
import MySQLdb

def populate_mysql_db():
    conn = MySQLdb.connect(host="localhost",
        user="myusername",passwd="mypassword",db="mydb")
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS mytable 
        (mycol1 varchar(100), mycol2 integer);
        ''')
    csv_reader = csv.reader(open('mycsvfile.csv', 'rb'), delimiter=',')
    for line in csv_reader:
        c.execute('''INSERT INTO mytable (mycol1, mycol2) 
            VALUES (%s, %s)''', (line[0],line[1]))
    c.close()
    conn.close()

if __name__ == "__main__":
    populate_mysql_db()

这篇关于在不使用load data命令的情况下填充数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆