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()
相关推荐
草莓熊Lotso1 小时前
Linux 基础 IO 初步解析:从 C 库函数到系统调用,理解文件操作本质
linux·运维·服务器·c语言·数据库·c++·人工智能
Cx330❀1 小时前
从零实现Shell命令行解释器:原理与实战(附源码)
大数据·linux·数据库·人工智能·科技·elasticsearch·搜索引擎
AAD555888996 小时前
数字仪表LCD显示识别与读数:数字0-9、小数点及单位kwh检测识别实战
python
开源技术8 小时前
Python Pillow 优化,打开和保存速度最快提高14倍
开发语言·python·pillow
岁岁种桃花儿8 小时前
MySQL从入门到精通系列:InnoDB记录存储结构
数据库·mysql
Li emily8 小时前
解决港股实时行情数据 API 接入难题
人工智能·python·fastapi
wfeqhfxz25887829 小时前
农田杂草检测与识别系统基于YOLO11实现六种杂草自动识别_1
python
jiunian_cn9 小时前
【Redis】hash数据类型相关指令
数据库·redis·哈希算法
mftang9 小时前
Python 字符串拼接成字节详解
开发语言·python
0思必得09 小时前
[Web自动化] Selenium设置相关执行文件路径
前端·爬虫·python·selenium·自动化