前面讲了链接库时遇到的一些问题,下面贴出代码,以供后面继续学习
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
import mysql.connector
import dns.resolver
#创建flask对象
app = Flask(__name__)
#配置flask配置对象中键:SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+mysqlconnector://user:password@host/test?charset=utf8"
#配置flask配置对象中键:SQLALCHEMY_COMMIT_TEARDOWN,设置为True,应用会自动在每次请求结束后提交数据库中变动
app.config['SQLALCHEMY_COMMIT_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
#获取SQLAlchemy实例对象,接下来就可以使用对象调用数据
db = SQLAlchemy(app)
#创建模型对象
class admin(db.Model):
id = Column(Integer,primary_key=True)
number = Column(String)
name = Column(String)
data = admin.query.filter_by(number = 'admin').first() #条件查询
print ('%s'%data.id + '--' + '%s'%data.number + '--' + '%s'%data.name)
打印结果:1–admin–管理员
或者使用以下代码:
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import mysql.connector
Base = declarative_base()
engine = create_engine('mysql+mysqlconnector://root:scw729295@127.0.0.1/test')
DBSession = sessionmaker(bind=engine)
session = DBSession()
class admin(Base):
__tablename__ = 'admin'
id = Column(Integer,primary_key=True)
number = Column(String)
name = Column(String)
admin = session.query(admin).all()
for i in admin:
print ('%s'%i.id + '--' + '%s'%i.number + '--' + '%s'%i.name)
打印结果:1–admin–管理员