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()
相关推荐
Swizard2 小时前
别再让你的 Python 傻等了:三分钟带你通过 asyncio 实现性能起飞
python
悄悄敲敲敲2 小时前
MySQL表的约束
数据库·mysql
鼠爷ねずみ2 小时前
SpringCloud前后端整体开发流程-以及技术总结文章实时更新中
java·数据库·后端·spring·spring cloud
九皇叔叔3 小时前
MySQL 数据库 Read View 详解
数据库·mysql·mvcc·read view
Darkershadow4 小时前
python学习之串口通信
python·学习
Elastic 中国社区官方博客4 小时前
Elasticsearch:圣诞晚餐 BBQ - 图像识别
大数据·数据库·elasticsearch·搜索引擎·ai·全文检索
cui_win4 小时前
Prometheus实战教程 - Redis 监控
数据库·redis·prometheus
3824278274 小时前
python:输出JSON
前端·python·json
JIngJaneIL5 小时前
基于java + vue个人博客系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
TG:@yunlaoda360 云老大5 小时前
华为云国际站代理商备份策略设置过程中遇到问题如何解决?
服务器·数据库·华为云