SQLAlchemy建完数据提交MySQL没反应

fromsqlalchemyimportcreate_engineHOSTusername='127.0.0.1'#ip地址PORT='3306'#端口号DATABASE... from sqlalchemy import create_engine

HOSTusername = '127.0.0.1' # ip地址
PORT = '3306' # 端口号
DATABASE = 'test' # 数据库名
USERusername = 'root' # 用户名
PASSWORD = 'root' # 用户登录密码

DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERusername, PASSWORD, HOSTusername, PORT, DATABASE)
engine = create_engine(DB_URI)

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base(engine)

from sqlalchemy import Column,Integer,String

class User(Base):
__tableusername__ = 'user'
id = Column(Integer,primary_key=True,autoincrement=True)
userusername = Column(String(50),nullable=False)
password = Column(String(100))

def __repr__(self):
return '<User(id="%s",userusername="%s",password="%s)>' % (self.id, self.userusername, self.password)

Base.metadata.create_all()

from sqlalchemy.orm import sessionmaker

Session = sessionmaker(engine)
session = Session

def add_user():
qa = User(username='qa', password='123456')
qb = User(username='qb', password='888888')
session.add(qa)
session.add(qb)
ls = [User(username='qc', password='888888'),
User(username='qd', password='666666')]
session.add_all(ls)
session.commit()
add_user()
有缩进,提交问题时显现,运行结果有一句
sqlalchemy.exc.InvalidRequestError: Class <class '__main__.User'> does not have a __table__ or __tablename__ specified and does not inherit from an existing table-mapped class.,是没有对应数据库表头嘛?英文不太好,数据库进去查找desc结构能看到,select * from user就什么都没有,不解
展开
 我来答
折柳成萌
高粉答主

2018-10-09 · 繁杂信息太多,你要学会辨别
知道顶级答主
回答量:4.4万
采纳率:96%
帮助的人:6356万
展开全部
python3下用flask-sqlalchemy对mysql数据库操作案例:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/db_name'
db = SQLAlchemy(app)

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)

def __init__(self, username, email):
self.username = username
self.email = email

def __repr__(self):
return '<User %r>' % self.username

admin = User('admin', 'admin@example.com')

db.create_all() # In case user table doesn't exists already. Else remove it.

db.session.add(admin)

db.session.commit() # This is needed to write the changes to database

User.query.all()

User.query.filter_by(username='admin').first()
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式