pandas1.1.5版本 to_sql mysql字段添加注释
时间: 2024-05-07 19:23:26 浏览: 142
在 pandas1.1.5 版本中,to_sql 方法不能够直接添加字段注释,需要通过调用 sqlalchemy 库的 DDL 类中的 text 方法来实现。
具体代码如下:
```python
from sqlalchemy import create_engine, text
# 创建数据库连接
engine = create_engine('mysql+pymysql://user:password@host:port/database_name')
# 创建数据表
df.to_sql(name='table_name', con=engine, if_exists='replace', index=False)
# 添加注释
with engine.connect() as con:
# 获取表结构
table_info = con.execute('SHOW CREATE TABLE table_name').fetchall()[0][1]
# 获取字段名
column_names = [i.split('`')[1] for i in table_info.split('\n')[1:-1]]
# 获取字段注释
column_comments = ['comment1', 'comment2', ...] # 需要自己定义每个字段的注释
# 更新字段注释
for i in range(len(column_names)):
con.execute(text(f'ALTER TABLE table_name MODIFY COLUMN `{column_names[i]}` {table_info.split("`")[i*2+3]} COMMENT :comment'), comment=column_comments[i])
```
其中,`column_comments` 列表需要自己定义每个字段的注释。
阅读全文
相关推荐
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)