在使用SQLAlchemy做MySQl数据库访问时,遇到了连接池的问题,导致MySQL连接达到最大可允许连接上限,连接拒绝情况。说一下我的应用情况,单线程访问数据库,在单个线程中会涉及到多次数据库操作,并且有个别操作非常耗时,为了避免数据库常连接问题,这里我们采取的方案是
每次重新连接数据库
-
-
1 2 3 4 5
|
engine = create_engine(self.conn_str, echo=False, pool_recycle=7200, pool_size=10) Session = sessionmaker() Session.configure(bind=engine, autocommit=True) session = Session() self.session = session
|
-
参考此文章
1
|
engine = create_engine(self.conn_str, echo=False, poolclass=NullPool)
|
-
针对第二个问题,应该修改为针对单个线程,共用一个engine, 对于每次数据库访问仅实例化不同的session即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
from sqlalchemy import Column, String, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.pool import NullPool import time
Base = declarative_base()
class User(Base):
def __init__(self, id, name): self.id = id self.name = name __tablename__ = 'user'
id = Column(String(20), primary_key=True) name = Column(String(20))
engine = create_engine("mysql://root:[email protected]:3306/local_test", echo=False, pool_recycle=7200)
DBSession = sessionmaker(bind=engine, autocommit=True)
print 'add record'
session = DBSession() session.begin(subtransactions=True)
new_user = User(id='5', name='Bob')
session.add(new_user)
session.commit()
session.close() time.sleep(10)
print 'query record'
session = DBSession() session.begin(subtransactions=True)
user = session.query(User).filter(User.id=='5').one()
print 'type:', type(user) print 'name:', user.name
session.close() time.sleep(10)
print 'delete record'
session = DBSession() session.begin(subtransactions=True)
session.delete(new_user) session.commit()
session.close() time.sleep(10)
|
-
-
-