如何使用Python在 SQLite 数据库中导入 CSV 文件?
在本文中,我们将学习如何使用Python从 CSV 文件导入数据并将其存储在 SQLite 数据库的表中。您可以从此处下载 CSV 文件,其中包含一些学生姓名和年龄的示例数据。
方法:
- 导入必要的模块
- 从 CSV 文件 DictReader() 读取数据
- 建立与数据库的连接。
sqliteConnection = sqlite3.connect('sql.db')
cursor = sqliteConnection.cursor()
- 创建学生表并使用 execute() 方法执行查询。
- 向表中插入数据
cursor.executemany("insert into student (name, age) VALUES (?, ?);", student_info)
- 从表中读取数据
- 并关闭数据库。
下面是实现:
Python3
import csv
import sqlite3
try:
# Import csv and extract data
with open('student_info.csv', 'r') as fin:
dr = csv.DictReader(fin)
student_info = [(i['NAME'], i['AGE']) for i in dr]
print(student_info)
# Connect to SQLite
sqliteConnection = sqlite3.connect('sql.db')
cursor = sqliteConnection.cursor()
# Create student table
cursor.execute('create table student(name varchar2(10), age int);')
# Insert data into table
cursor.executemany(
"insert into student (name, age) VALUES (?, ?);", student_info)
# Show student table
cursor.execute('select * from student;')
# View result
result = cursor.fetchall()
print(result)
# Commit work and close connection
sqliteConnection.commit()
cursor.close()
except sqlite3.Error as error:
print('Error occured - ', error)
finally:
if sqliteConnection:
sqliteConnection.close()
print('SQLite Connection closed')
输出: