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()
相关推荐
2401_832365527 分钟前
JavaScript中rest参数(...args)取代arguments的优势
jvm·数据库·python
Sirius.z9 分钟前
第J3周:DenseNet121算法详解
python
2301_7796224124 分钟前
Go语言怎么用信号量控制并发_Go语言semaphore信号量教程【入门】
jvm·数据库·python
2301_7662834436 分钟前
c++如何将控制台输出保存到文件_cout重定向到txt【详解】
jvm·数据库·python
北极的冰箱39 分钟前
MySQL Ver 8.0.41 for macos14.7密码遗忘
数据库·mysql
XDH_CS1 小时前
MySQL 8.0 安装与 MySQL Workbench 使用全流程(超详细教程)
开发语言·数据库·mysql
treacle田2 小时前
达梦数据库-统计信息收集-记录
数据库·达梦数据库统计信息收集
小康小小涵2 小时前
基于ESP32S3实现无人机RID模块底层源码编译
linux·开发语言·python
lzjava20242 小时前
Python的函数
开发语言·python
审判长烧鸡2 小时前
PostgreSQL之索引/函数/触发器
数据库·postgresql·触发器·函数·索引