# file: load.py
# 把文件中的数据导入到数据库中
# 输入参数:导入到哪张表,导入哪个文件
from MySQLdb import *
# 连接数据库
db = connect(host = 'localhost',
user = 'root',
passwd = 'colorfulgreen',
db = 'test')
# 获取数据库游标
cur = db.cursor()
# 获取当前使用的数据库名字
database = cur.execute('select database()') # 执行语句
database = cur.fetchall() # 从游标中读取数据
print 'the current database: %s' %(database[0]) # 输出
# 列出数据库中的所有表
show_tables = cur.execute('show tables')
show_tables = cur.fetchall()
print 'all tables: '
for tmp_line in show_tables:
print tmp_line[0]
# 选择表
load_to_table = raw_input('please select the table to load to:')
# print 'the data will be load to %s' %load_to_table
# 输入要导入的文件
load_from_file = raw_input('plese input the file path to load from:')
# print 'the data will be load from %s' %load_from_file
# 导入
sql = 'load data local infile \'' + load_from_file + '\' into table ' + load_to_table # 注意文件名两边要有引号!!!
load_num = cur.execute(sql)
print '%d records have been loaded' %load_num