1)将SQLite数据库练习里,学生管理数据库系统中的表全部新建到MySQL里,并将数据导入到数据库中。用Python实现
时间: 2024-05-13 10:18:21 浏览: 216
首先,我们需要在MySQL中新建数据库和表。假设我们新建了一个名为`student`的数据库,并在其中创建了一个名为`student_info`的表,表结构如下:
```mysql
CREATE TABLE student_info (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
age INT(11) NOT NULL,
gender VARCHAR(10) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
```
接下来,我们需要将SQLite中的数据导入到MySQL中。我们可以使用Python的`sqlite3`和`pymysql`模块来实现这个过程。具体步骤如下:
1. 连接SQLite数据库并查询数据。
```python
import sqlite3
# 连接SQLite数据库
conn_sqlite = sqlite3.connect('student.db')
# 查询数据
cursor_sqlite = conn_sqlite.cursor()
cursor_sqlite.execute('SELECT * FROM student')
students = cursor_sqlite.fetchall()
# 关闭连接
cursor_sqlite.close()
conn_sqlite.close()
```
2. 连接MySQL数据库并插入数据。
```python
import pymysql
# 连接MySQL数据库
conn_mysql = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='student', charset='utf8')
cursor_mysql = conn_mysql.cursor()
# 插入数据
for student in students:
sql = "INSERT INTO student_info (name, age, gender) VALUES (%s, %s, %s)"
cursor_mysql.execute(sql, (student[1], student[2], student[3]))
# 提交事务并关闭连接
conn_mysql.commit()
cursor_mysql.close()
conn_mysql.close()
```
完整代码如下:
```python
import sqlite3
import pymysql
# 连接SQLite数据库
conn_sqlite = sqlite3.connect('student.db')
# 查询数据
cursor_sqlite = conn_sqlite.cursor()
cursor_sqlite.execute('SELECT * FROM student')
students = cursor_sqlite.fetchall()
# 关闭连接
cursor_sqlite.close()
conn_sqlite.close()
# 连接MySQL数据库
conn_mysql = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='student', charset='utf8')
cursor_mysql = conn_mysql.cursor()
# 插入数据
for student in students:
sql = "INSERT INTO student_info (name, age, gender) VALUES (%s, %s, %s)"
cursor_mysql.execute(sql, (student[1], student[2], student[3]))
# 提交事务并关闭连接
conn_mysql.commit()
cursor_mysql.close()
conn_mysql.close()
```
运行代码后,MySQL数据库中的`student_info`表中就会有和SQLite数据库中相同的数据。
阅读全文