第三题:(数据库) 1.在MySQL数据库中建表student,添加name,stundentlD,birt h, class,remarks字段 2.读取第二题的数据文件document.txt 3.连接数据库,将文件中的内容全部存入student表中,学号作为主键 4.查询数据库中student中的信息内容,并打印 5.查询student中的信息并重新写入到新的文件student.txt中
时间: 2024-02-09 14:10:08 浏览: 24
好的,我会依次为您解答这个问题。
1. 在MySQL数据库中建表student,添加name,studentID,birth,class,remarks字段
建表语句如下:
```
CREATE TABLE student (
studentID INT(11) NOT NULL,
name VARCHAR(50) NOT NULL,
birth DATE NOT NULL,
class VARCHAR(50) NOT NULL,
remarks VARCHAR(255),
PRIMARY KEY (studentID)
);
```
2. 读取第二题的数据文件document.txt
您需要先确定document.txt的存储路径,然后可以使用Python中的文件操作函数来读取文件内容。假设文件存储在当前目录下,可以使用如下代码读取文件内容:
```
with open('document.txt', 'r', encoding='utf-8') as f:
content = f.read()
```
3. 连接数据库,将文件中的内容全部存入student表中,学号作为主键
在Python中使用MySQL数据库需要先安装相应的库,如`pymysql`。连接数据库的代码如下:
```
import pymysql
# 建立连接
conn = pymysql.connect(host='localhost', user='root', password='123456', database='test', charset='utf8')
# 获取游标
cursor = conn.cursor()
# 将读取到的内容按行分割
lines = content.split('\n')
# 循环插入数据
for line in lines:
# 按照逗号分割各个字段
fields = line.split(',')
# 如果字段数量不足5个,说明该行数据不合法,跳过
if len(fields) < 5:
continue
# 将数据插入数据库
sql = f"INSERT INTO student (studentID, name, birth, class, remarks) VALUES ('{fields[0]}', '{fields[1]}', '{fields[2]}', '{fields[3]}', '{fields[4]}')"
cursor.execute(sql)
# 提交事务
conn.commit()
# 关闭游标和连接
cursor.close()
conn.close()
```
4. 查询数据库中student中的信息内容,并打印
查询数据库的代码如下:
```
import pymysql
# 建立连接
conn = pymysql.connect(host='localhost', user='root', password='123456', database='test', charset='utf8')
# 获取游标
cursor = conn.cursor()
# 查询数据
sql = "SELECT * FROM student"
cursor.execute(sql)
# 获取查询结果
results = cursor.fetchall()
# 打印查询结果
for row in results:
studentID = row[0]
name = row[1]
birth = row[2]
class_ = row[3]
remarks = row[4]
print(f"学号:{studentID},姓名:{name},出生日期:{birth},班级:{class_},备注:{remarks}")
# 关闭游标和连接
cursor.close()
conn.close()
```
5. 查询student中的信息并重新写入到新的文件student.txt中
重新写入文件的代码如下:
```
import pymysql
# 建立连接
conn = pymysql.connect(host='localhost', user='root', password='123456', database='test', charset='utf8')
# 获取游标
cursor = conn.cursor()
# 查询数据
sql = "SELECT * FROM student"
cursor.execute(sql)
# 获取查询结果
results = cursor.fetchall()
# 将查询结果写入文件
with open('student.txt', 'w', encoding='utf-8') as f:
for row in results:
studentID = row[0]
name = row[1]
birth = row[2]
class_ = row[3]
remarks = row[4]
line = f"{studentID},{name},{birth},{class_},{remarks}\n"
f.write(line)
# 关闭游标和连接
cursor.close()
conn.close()
```
以上就是完整的解答,希望能对您有所帮助。