开发者

Populating a database without the load data command

How do I populate data (.csv f开发者_高级运维iles) into MySql (Windows 5.1) without using the load data command?


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

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()


Try this:

grant file on *.* to youruser@localhost identified by 'yourpassword';


What are the tools you have? Any kind of scripting language? Any management interface, like MySQL Admin?

There are a lot of ways to load data into database. But we need to know what tools you have at hand.

EDIT

One of your options is to make a .sql batch file. The quickest to load approach would be using prepared statements. Check below how.

PREPARE massInsert 'INSERT INTO mytable (field1, field2, field3...) VALUES (?,?,?,?...)';
EXECUTE massInsert (value1, value2...);
many lines
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜