当您不知道有多少列时,将CSV转换为SQLite

时间:2018-03-29 19:20:32

标签: python sqlite csv

下面的代码适用于我目前正在处理的测试程序,因为我知道csv文件中有多少列以及标题是什么。我试图弄清楚如何修改代码以获取任何csv文件,而不知道有多少列,仍然将其转换为sqlite数据库。我知道大熊猫可以很简单地做到这一点,但我正在努力学习另一条路线。谢谢。

import sqlite3, csv

con = sqlite3.connect("person.db")
cur = con.cursor()

cur.execute("""CREATE TABLE person (memberNum STR,lastName STR,firstName 
STR,streetAddress STR, city STR, state STR,zipCode STR,phone 
STR,favoriteStore STR,dateJoined STR, duesPaid STR, PRIMARY KEY(memberNum))""")

with open('Members.csv','r') as person_table:
    dr = csv.DictReader(person_table, delimiter=',') # comma is default delimiter
    to_db = [(i['Member #'], i['Last Name'], i['First Name'], i['Street Address'], i['City'], i['State'], i['Zip Code'], i['Phone'], i['Favorite Store'], i['Date Joined'], i['Dues Paid']) for i in dr]

cur.executemany("INSERT INTO person VALUES (?,?,?,?,?,?,?,?,?,?,?);", to_db)
con.commit()

#Select statment to query the db
cursor = con.execute("Select * from person order by lastName")
for row in cursor:
   print "ID = ", row[0]
   print "Last Name = ", row[1]
   print "First Name = ", row[2]
   print "Phone Number = ", row[7], "\n"

1 个答案:

答案 0 :(得分:2)

在在SQLite中执行CREATE TABLE命令之前获取列名。然后构造CREATE TABLE语句并执行它。确保在CREATE TABLEINSERT语句中以相同的方式订购字典键,否则您可能会在错误的列中输入值。