Python如何实现将SQLite数据库练习里,学生管理数据库系统中的表全部新建到MySQL里,并将数据导入到数据库中
时间: 2024-05-06 16:15:53 浏览: 132
要将SQLite数据库中的表全部新建到MySQL中,并将数据导入到MySQL数据库中,可以使用Python中的sqlite3和pymysql库。
首先,我们需要连接到SQLite数据库,获取所有表格的名称。可以使用如下代码:
```python
import sqlite3
# 连接到SQLite数据库
sqlite_conn = sqlite3.connect('students.db')
sqlite_cursor = sqlite_conn.cursor()
# 获取所有表格名称
sqlite_cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
table_names = [x[0] for x in sqlite_cursor.fetchall()]
```
然后,我们需要连接到MySQL数据库,并使用CREATE TABLE语句创建新表。可以使用如下代码:
```python
import pymysql
# 连接到MySQL数据库
mysql_conn = pymysql.connect(host='localhost', user='user', password='password', database='students')
mysql_cursor = mysql_conn.cursor()
# 创建新表
for table_name in table_names:
sqlite_cursor.execute(f"PRAGMA table_info({table_name})")
columns = sqlite_cursor.fetchall()
create_table_sql = f"CREATE TABLE {table_name} ("
for column in columns:
create_table_sql += f"{column[1]} {column[2]}, "
create_table_sql = create_table_sql[:-2] + ")"
mysql_cursor.execute(create_table_sql)
```
最后,我们需要将SQLite数据库中的数据导入到MySQL数据库中。可以使用如下代码:
```python
# 导入数据
for table_name in table_names:
sqlite_cursor.execute(f"SELECT * FROM {table_name}")
rows = sqlite_cursor.fetchall()
for row in rows:
insert_sql = f"INSERT INTO {table_name} VALUES ("
for value in row:
if isinstance(value, str):
insert_sql += f"'{value}', "
else:
insert_sql += f"{value}, "
insert_sql = insert_sql[:-2] + ")"
mysql_cursor.execute(insert_sql)
# 提交更改
mysql_conn.commit()
# 关闭连接
mysql_conn.close()
sqlite_conn.close()
```
完整代码如下:
```python
import sqlite3
import pymysql
# 连接到SQLite数据库
sqlite_conn = sqlite3.connect('students.db')
sqlite_cursor = sqlite_conn.cursor()
# 获取所有表格名称
sqlite_cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
table_names = [x[0] for x in sqlite_cursor.fetchall()]
# 连接到MySQL数据库
mysql_conn = pymysql.connect(host='localhost', user='user', password='password', database='students')
mysql_cursor = mysql_conn.cursor()
# 创建新表
for table_name in table_names:
sqlite_cursor.execute(f"PRAGMA table_info({table_name})")
columns = sqlite_cursor.fetchall()
create_table_sql = f"CREATE TABLE {table_name} ("
for column in columns:
create_table_sql += f"{column[1]} {column[2]}, "
create_table_sql = create_table_sql[:-2] + ")"
mysql_cursor.execute(create_table_sql)
# 导入数据
for table_name in table_names:
sqlite_cursor.execute(f"SELECT * FROM {table_name}")
rows = sqlite_cursor.fetchall()
for row in rows:
insert_sql = f"INSERT INTO {table_name} VALUES ("
for value in row:
if isinstance(value, str):
insert_sql += f"'{value}', "
else:
insert_sql += f"{value}, "
insert_sql = insert_sql[:-2] + ")"
mysql_cursor.execute(insert_sql)
# 提交更改
mysql_conn.commit()
# 关闭连接
mysql_conn.close()
sqlite_conn.close()
```
注意,这里的MySQL数据库连接信息需要根据实际情况修改。
阅读全文