20210150章明一班男 20210123李悦灵二班女 20210913欧阳紫玉一班女 读取文本文件data.txt,将学号、姓名、班级、性别插入到数据库Student.db的stu表中 import salite3 con = sqlite3.connect('student.db' cur = con.cursor0) cur.execute('create table if not exists stus(id primary key,name text,cla text,sex text)fr = open(dat.txt',r) for line in frreadlines(): L=len(line) if line[-1]=='n' L=L-1line=line[o:L]xh=line[0:8] xm=line[8:L-3] bj=line[L xb=line[L-1:]print(xh,xm,xb) values(?,?,?,?),(xh,xm,bj,xb))cur.execute(insert intofr.close()con.commit0)cur.close() con.close()
时间: 2024-02-09 15:13:28 浏览: 23
在您提供的代码中,存在一些语法错误和逻辑错误,可以参考以下代码进行修改:
```python
import sqlite3
conn = sqlite3.connect('Student.db')
cur = conn.cursor()
cur.execute('''CREATE TABLE IF NOT EXISTS stu
(id TEXT PRIMARY KEY,
name TEXT,
cla TEXT,
sex TEXT);''')
with open('data.txt', 'r') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
xh = line[0:8]
xm = line[8:-3]
bj = line[-3:-1]
xb = line[-1:]
cur.execute("INSERT INTO stu (id, name, cla, sex) VALUES (?, ?, ?, ?)", (xh, xm, bj, xb))
conn.commit()
cur.close()
conn.close()
```
代码的改动主要包括:
1. 修改了数据库文件名为 `Student.db`;
2. 修改了 `CREATE TABLE` 语句中的主键类型为 `TEXT`;
3. 修改了 `INSERT INTO` 语句中的参数顺序;
4. 修改了读取文件的方式,使用了 `with open()`;
5. 对读取的每一行进行了 `strip()` 操作,去除了多余的空格和换行符;
6. 修改了提取姓名、班级和性别的逻辑,使用了字符串的切片操作。
请注意,以上代码仅供参考,您需要根据自己的具体情况进行修改和调试。