SqlAlchemy “Too many connections”
2019-06-12:真 有用的是这个:
https://blog.csdn.net/weiwangchao_/article/details/80185009
1、在使用 create_engine创建引擎时,如果默认不指定连接池设置的话,一般情况下,SQLAlchemy会使用一个 QueuePool绑定在新创建的引擎上。并附上合适的连接池参数。
2、在这种情况下,当你使用了session后就算显式地调用session.close(),也不能把连接关闭。连接会由QueuePool连接池进行管理并复用。
3、如果想禁用SQLAlchemy提供的数据库连接池,只需要在调用create_engine是指定连接池为NullPool,SQLAlchemy就会在执行session.close()后立刻断开数据库连接。当然,如果session对象被析构但是没有被调用session.close(),则数据库连接不会被断开,直到程序终止。
from sqlalchemy.pool import NullPool #连接数据库
def getEngine():
engine = create_engine('mysql://root:123456@127.0.0.1/baa?charset=utf8mb4', poolclass=NullPool, echo=False)
#print(engine)
return engine def getSession():
engine = getEngine()
BaseMode.metadata.create_all(engine)## 数据库生成表
# Session = sessionmaker(bind=engine)
# session = Session() DBSession = sessionmaker(bind=engine)
session = DBSession() return session
File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\connections.py", line 393, in check_error
err.raise_mysql_exception(self._data)
File "C:\Users\user\AppData\Local\Programs\Python\Python36\lib\site-packages\pymysql\err.py", line 107, in raise_mysql_exception
raise errorclass(errno, errval)
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1040, 'Too many connections') (Background on this error at: http://sqlalche.me/e/e3q8) Process finished with exit code 1
1、pandas dataframe to_sql()
#连接数据库
def getEngine():
engine = create_engine('mysql://root:123456@127.0.0.1/databaseName?charset=utf8mb4',echo=False)
#print(engine)
return engine
def getSession():
engine = getEngine()
BaseMode.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
return session
def get_stock_daily(ts_code, start_date,end_date,startTime):
# print( ts_code + " " + str(start_date) + " " + str(end_date))
api = ts.pro_api(token) try:
df = ts.pro_bar(pro_api=api, ts_code=ts_code, start_date=start_date, end_date=end_date) # 【获取数据】
if df is None:
print("没有获取到数据")
return None print("data count: " + str(len(df)))
df['trade_date'] = pd.to_datetime(df['trade_date']) # 交易日期字符串转换成日期格式
conn = cheDbUtil.getEngine()
try:
df.to_sql('b_stock_daily', con=conn, if_exists='append', index=False) # replace/append/fail 【save】
except Exception as e:
traceback.print_exc()
print("get_stock_daily() in BaaBusiniessPro.py XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
return None
finally:
conn.dispose()
except Exception as e:
sleepNeed = 60
print("Start to sleep " + str(sleepNeed) + ' 秒')
print("当前耗时: " + str(round((time.time() - startTime), 2) / 60) + ' 分钟')
time.sleep(sleepNeed) # 休眠 ? 秒
2、SqlAlchemy 操作 mysql
#获取日行情最后一条记录的日期
def getMaxTradeDateForStockDaily(ts_code):
try:
session = getSession()
rows = session.query(func.max(StockDaily.trade_date)).filter(StockDaily.ts_code == ts_code).one()
# print(str(len(rows)))
# print(type(rows))
# print(str(rows))
if rows is not None and len(rows) == 1:
return rows[0]
return None
except Exception as e:
traceback.print_exc()
print("getMaxTradeDateForStockDaily() XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
return None
finally:
session.close()
SqlAlchemy “Too many connections”的更多相关文章
- sqlalchemy学习
sqlalchemy官网API参考 原文作为一个Pythoner,不会SQLAlchemy都不好意思跟同行打招呼! #作者:笑虎 #链接:https://zhuanlan.zhihu.com/p/23 ...
- Python操作Redis、Memcache、RabbitMQ、SQLAlchemy
Python操作 Redis.Memcache.RabbitMQ.SQLAlchemy redis介绍:redis是一个开源的,先进的KEY-VALUE存储,它通常被称为数据结构服务器,因为键可以包含 ...
- 3.SQLAlchemy文档-SQLAlchemy Core(中文版)
这里的文描述了关于SQLAlchemy的的SQL渲染引擎的相关内容,包括数据库API的集成,事务的集成和数据架构描述服务.与以领域为中心的ORM使用模式相反,SQL表达式语言提供了一个数据构架为中心的 ...
- SQLAlchemy on the way
SQLAlchemy Trial This is a great ORM ( Object-Relational Mapper ) which is compatible with xxxx and ...
- Python 之路:Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy
一.Memcached Memcached是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负债.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速 ...
- python 全栈开发,Day142(flask标准目录结构, flask使用SQLAlchemy,flask离线脚本,flask多app应用,flask-script,flask-migrate,pipreqs)
昨日内容回顾 1. 简述flask上下文管理 - threading.local - 偏函数 - 栈 2. 原生SQL和ORM有什么优缺点? 开发效率: ORM > 原生SQL 执行效率: 原生 ...
- 深入研究sqlalchemy连接池
简介: 相对于最新的MySQL5.6,MariaDB在性能.功能.管理.NoSQL扩展方面包含了更丰富的特性.比如微秒的支持.线程池.子查询优化.组提交.进度报告等. 本文就主要探索MariaDB当中 ...
- sqlalchemy 简介
#! /usr/bin/env python3 # -*- coding:utf-8 -*- #use SQLAlchemy #ORM:Object-Relational Mapping ,把关系数据 ...
- sqlalchemy学习-- 重要参数
Base = declarative_base 基类: 1.存储表 2.建立class-Table 的映射关系 engine = create_engine('mysql://root:root@lo ...
随机推荐
- 查看当前的app运行的是哪个Activity
1.确认手机连接了adb-->检查方式:adb devices 2.手机运行任意app,随意进入一个页面 3.此时cmd运行:adb shell "dumpsys window | g ...
- P1101 单词方阵 简单dfs
题目描述 给一n \times nn×n的字母方阵,内可能蕴含多个“yizhong”单词.单词在方阵中是沿着同一方向连续摆放的.摆放可沿着 88 个方向的任一方向,同一单词摆放时不再改变方向,单词与单 ...
- day33 网络编程之线程,并发以及selectors模块io多路复用
io多路复用 selectors模块 概要: 并发编程需要掌握的知识点: 开启进程/线程 生产者消费者模型!!! GIL全局解释器锁(进程与线程的区别和应用场景) 进程池线程池 IO模型(理论) 1 ...
- POJ 2594 Treasure Exploration (Floyd+最小路径覆盖)
<题目链接> 题目大意: 机器人探索宝藏,有N个点,M条边.问你要几个机器人才能遍历所有的点. 解题分析: 刚开始还以为是最小路径覆盖的模板题,但是后面才知道,本题允许一个点经过多次,这与 ...
- django+mongodb 内置用户控制
0x01 项目:django2.1 数据库:mongodb 这是一个很蛋疼的组合 mongodb并非官方支持使用的数据库,这意味着要使用user group permissions等进行用户和权限控制 ...
- Spring ConfigurationClassPostProcessor Bean解析及自注册过程
一.Bean的自注册过程 二.自注册过程说明 ConfigurationClassParser解析流程 1.处理@PropertySources注解,配置信息的解析 2.处理@ComponentSc ...
- ServiceNow在中国还有没有模仿者?
美国版的“ServiceNow”:https://www.servicenow.com 中国版的“ServiceHot” :http://www.itsmcn.com
- 【PYTHON】 Missing parentheses in call to 'print'
Microsoft Windows [版本 10.0.15063] (c) 2017 Microsoft Corporation.保留所有权利. C:\Users\Jam>python Pyth ...
- 南方IT学校期末PCB结课项目考试(实操)说明书
南方IT学校期末结课项目考试(实操)说明书(一) 课程:<印制电路板设计技术>(二) 项目:笔记本电脑电源适配器的印制电路板设计(三) 背景说明:如今笔记本已经进入千家万户,作为给电脑充电 ...
- nodejs,mongodb不同时区问题
问题:不同国家,使用不同时区,而服务器代码却在国内,跨时区日期不同,根据日期查询,查询不到数据了 1.mongodb存储的new Date()是UTC时间,也就是0时区的时间,世界标准时间 2.参考m ...