在python sqlalchemy的实践经验里面,我们都是通过模型去生成数据库表。但我们在取数的时候,写sql语句的时候,就可以用ORM。
但我们还有场景就是数据库已经存在,需要对数据进行增删改查的操作,这时候不光是用SQL,更想用的还是上面说到的sqlalchemy的ORM。
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
# db1 - works ok.
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://user:password@localhost/SiPMCalibration'
# db2 - not working.
app.config['SQLALCHEMY_BINDS'] = {
'db2': 'mysql://user:password@localhost/Run8Chan'
}
db = SQLAlchemy(app)
db.Model.metadata.reflect(db.engine)
# Setup the model for the pre-existing table.
class sipm_calibration(db.Model):
__table__ = db.Model.metadata.tables['Calibration']
# Some code to retrive the most recent 100 entries and print their headers (i.e keys)
query = db.session.query(sipm_calibration).order_by(sipm_calibration.ID.desc()).limit(100)
print db.session.execute(query).keys() # Works fine.
#---------------------
# All ok so far - try again for the second database via binding.
class run_entry(db.Model):
__bind_key__ = 'db2'
__table__ = db.Model.metadata.tables['Runs']
query = db.session.query(run_entry).order_by(run_entry.ID.desc()).limit(100)
print db.session.execute(query).keys()

