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()
相关推荐
倔强青铜三19 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户2519162427111 天前
Python之语言特点
python
RestCloud1 天前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
刘立军1 天前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
RestCloud1 天前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence1 天前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python