pandas处理完的表格保存到mysql中
时间: 2023-06-16 13:06:59 浏览: 90
可以使用 pandas 提供的 `to_sql()` 方法来将 DataFrame 保存到 MySQL 数据库中。
首先需要安装 `mysql-connector-python` 包,然后按照以下步骤操作:
1. 导入必要的库:
```python
import pandas as pd
import mysql.connector
from mysql.connector import Error
```
2. 连接到 MySQL 数据库:
```python
try:
connection = mysql.connector.connect(host='localhost',
database='mydatabase',
user='myusername',
password='mypassword')
if connection.is_connected():
print('Connected to MySQL database')
except Error as e:
print(e)
```
3. 从 MySQL 数据库中读取数据到 DataFrame:
```python
df = pd.read_sql('SELECT * FROM mytable', connection)
```
4. 处理 DataFrame 数据
5. 将 DataFrame 保存到 MySQL 数据库中:
```python
df.to_sql('newtable', connection, if_exists='replace', index=False)
```
其中,参数说明:
- `'newtable'` 表示新建的表格名称;
- `connection` 表示连接到的 MySQL 数据库连接对象;
- `if_exists='replace'` 表示如果表格已经存在则替换原有表格;
- `index=False` 表示不将 DataFrame 的索引保存到 MySQL 数据库中。
完整代码示例:
```python
import pandas as pd
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='mydatabase',
user='myusername',
password='mypassword')
if connection.is_connected():
print('Connected to MySQL database')
df = pd.read_sql('SELECT * FROM mytable', connection)
# 处理 DataFrame 数据
df.to_sql('newtable', connection, if_exists='replace', index=False)
except Error as e:
print(e)
finally:
if connection.is_connected():
connection.close()
print('MySQL database connection closed')
```
最后记得关闭数据库连接。