pysqlite从csv文件获取列名

时间:2018-06-27 16:12:33

标签: python python-3.x pysqlite

我有一个csv文件,试图从中将数据加载到pysqlite数据库中。我无法找到一种方法来提取文件的第一行并将其作为表的列标题自动添加到数据库中。我必须在代码本身中“手动”输入名称,这对于1-2列是可以的,但是在数十或数百列时变得很麻烦。这是我的代码:

import sqlite3
import csv

f_n = 'test_data_1.csv'
f = open( f_n , 'r' )
csv_reader = csv.reader(f)
header = next( csv_reader )

sqlite_file = 'survey_test_db.sqlite'
table_name01 = 'test_survey_1'

field_01 = 'analyst_name'
field_type_01 = 'text'
field_02 = 'question_name'
field_type_02 = 'text'

conn = sqlite3.connect( sqlite_file )
c = conn.cursor()
c.execute('CREATE TABLE {tn}({nf_01} {ft_01},{nf_02} {ft_02})'\
.format(tn = table_name01 , nf_01 = field_01 , ft_01 = field_type_01, nf_02 = field_02 , ft_02 = field_type_02 ))

for row in csv_reader:
 c.execute("INSERT INTO test_survey_1 VALUES (?,?)",row)
f.close()

for row in c.execute('SELECT * FROM test_survey_1'):
 print(row)

conn.commit()
conn.close()

2 个答案:

答案 0 :(得分:0)

c.execute('CREATE TABLE {tn}({fieldlist})'.format(
    tn=table_name01, 
    fieldlist=', '.join('{} TEXT'.format(name) for name in header),
))

或者使用旨在简化此类操作的ORM。 SQLAlchemy示例:

t = Table(table_name01, meta, *(Column(name, String()) for name in header))
t.create()

答案 1 :(得分:0)

您可以使用pandas将csv文件读入DataFrame,然后导出 到sqlite

import sqlite3
import pandas as pd

sqlite_file = 'survey_test_db.sqlite'
table_name01 = 'test_survey_1'

conn = sqlite3.connect(sqlite_file)

pd.read_csv('test_data_1.csv').to_sql(table_name01, con=con)