有数据文件student.csv,数据文件中包含学生学号,姓名,专业,出生年月,学制,学费等数据,请设计程序将此文件中的数据导入SQLite数据库或MySQL数据库stu.db的表data中,请设计程序将此文件中的数据导入SQLite数据库
时间: 2024-03-27 11:34:54 浏览: 80
好的,我会给你提供一个Python脚本,可以将student.csv文件中的数据导入到SQLite数据库中。
首先,你需要在Python中安装sqlite3模块,可以通过以下命令进行安装:
```
pip install sqlite3
```
接下来,你可以使用以下代码将数据导入SQLite数据库:
```python
import csv
import sqlite3
# 连接数据库
conn = sqlite3.connect('stu.db')
# 创建表
conn.execute('''CREATE TABLE data
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
MAJOR TEXT NOT NULL,
BIRTH TEXT NOT NULL,
LENGTH REAL NOT NULL,
FEE REAL NOT NULL);''')
# 读取CSV文件并将数据插入到数据库中
with open('student.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
ID, NAME, MAJOR, BIRTH, LENGTH, FEE = row
conn.execute("INSERT INTO data (ID, NAME, MAJOR, BIRTH, LENGTH, FEE) \
VALUES (?, ?, ?, ?, ?, ?)", (ID, NAME, MAJOR, BIRTH, LENGTH, FEE))
conn.commit()
# 关闭数据库连接
conn.close()
print("数据导入完成!")
```
这段代码会将student.csv文件中的数据导入到名为stu.db的数据库中,表名为data。请确保student.csv文件与Python脚本在同一个目录下,并且student.csv文件中的数据格式与表中的数据类型对应。
阅读全文
相关推荐

















