python使用read_sql与to_sql读写数据库

文章目录

详细说明

使用pandas读写数据库的方法(以Mysql为例)如下:

  • 首先是打包一个工具函数:

    py 复制代码
    import pandas as pd
    import numpy as np
    from sqlalchemy import create_engine, text
    
    
    def get_sql_engine():
        # 数据库
        mysql_config = {
            "db": "test_db",
            "host": "127.0.0.1",
            "user": "test_user",
            "password": "test_pass",
            "port": 3306,
        }
        engine = create_engine(
            "mysql+pymysql://{}:{}@{}:{}/{}".format(mysql_config['user'], mysql_config['password'], mysql_config['host'],
                                                    mysql_config['port'], mysql_config['db']))
        return engine
  • 读取数据库.read_sql()的方法:

    py 复制代码
    engine = get_sql_engine()
    
    # ======== 写入 ===========
    data_df = pd.DataFrame(np.random.random(size=(100, 5)))
    data_df.to_sql('test_data_df', con=engine, if_exists='replace', index=False)
  • 读取数据库read_sql()的方法:

    py 复制代码
     data_df = pd.read_sql_query(text('select * from test_data_df'), con=engine.connect())

    在读取的时候容易报错,有几个要点:

    1. 首先导入from sqlalchemy import text,然后以text(sql语句)的形式传入第一个参数

    2. 在第二个参数需要使用engine.connect()

示例程序

py 复制代码
import pandas as pd
import numpy as np
from sqlalchemy import create_engine, text


def get_sql_engine():
    # 数据库
    mysql_config = {
        "db": "test_db",
        "host": "127.0.0.1",
        "user": "test_user",
        "password": "test_pass",
        "port": 3306,
    }
    engine = create_engine(
        "mysql+pymysql://{}:{}@{}:{}/{}".format(mysql_config['user'], mysql_config['password'], mysql_config['host'],
                                                mysql_config['port'], mysql_config['db']))
    return engine


def main():
    engine = get_sql_engine()
    # ======== 写入 ===========
    data_df = pd.DataFrame(np.random.random(size=(100, 5)))
    data_df.to_sql('test_data_df', con=engine, if_exists='replace', index=False)
    # ======== 读取 ===========
    data_df = pd.read_sql_query(text('select * from test_data_df'), con=engine.connect())


if __name__ == '__main__':
    main()
相关推荐
默_笙3 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
qq_426003963 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫3 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技3 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
这个DBA有点耶3 天前
MVCC深入:Read View、版本链与快照读——InnoDB并发控制的内核
数据库·mysql·架构
DBA_G3 天前
从地面到云霄:GBase数据库在民航三大场景的落地实践
数据库
自由能燃气设备3 天前
商用全预混低氮冷凝锅炉免费方案vs付费方案对比+选型避坑指南
大数据·数据库·人工智能
只睡四小时3 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
科创致远3 天前
科创致远 ESOP 系统核心效能与实战价值展示
大数据·数据库·人工智能·精益工程