【发布时间】:2013-05-22 12:37:11
【问题描述】:
我有一个包含许多列的 csv 文件,我想将两个导入一个表,十个导入另一个,十个导入另一个。我怎样才能修改下面的代码以使其具有选择性?我正在考虑使用 if/elif 语句通过第一行数据来识别列,但我不确定这是最好/最简单的解决方案。
import csv
import MySQLdb
# open the connection to the MySQL server.
# using MySQLdb
mydb = MySQLdb.connect(host='hostinfo',
user='myusername',
passwd='mypw',
db='mydatabase')
cursor = mydb.cursor()
# read the presidents.csv file using the python
# csv module http://docs.python.org/library/csv.html
csv_data = csv.reader(file('CHN.csv'))
# execute the for clicle and insert the csv into the
# database.
for row in csv_data:
cursor.execute('''INSERT INTO INDICATORS (INDICATORNAME, INDICATORCODE)
VALUES (%s, %s)''', row)
#close the connection to the database.
mydb.commit()
cursor.close()
print "Import to MySQL is over"
【问题讨论】:
-
所以你想将元素 0 和 1 导入到 table1,2 到 11 到 table2,12 到 12 到 table3?或者是否有任何变化?第一行数据有什么特别之处?你有例子吗?
-
我是新手,所以感谢您的帮助和耐心。我有一个超过 50 列的 csv。我想将前两列拉到一个名为 Indicators 的 MySQL 表中。我想将接下来的 10 列拉到另一个名为 Sixties 的表中。我不知道该怎么做。
-
这里是第一行数据的示例(但不是所有列,因为它到 2012 年): 指标名称 指标代码 1960 1961 1962 1963 1964 1965 1966 1967 1968
标签: python mysql csv mysql-python