sqlalchemy插入数据不起作用

时间:2016-08-17 12:44:02

标签: python database insert sqlalchemy

在models.py中我定义了:

class slidephoto(db.Model):
    __tablename__ = 'slide_photo'
    id = db.Column(db.Integer, primary_key=True)
    uid = db.Column(db.Integer, nullable=False)
    photo = db.Column(db.String(collation='utf8_bin'), nullable=False)

    def __init__(self, uid, photo):
        self.uid = uid
        self.photo = photo

    def __repr__(self):
        return "{'photo': " + str(self.photo) + "}"

我选择这样的数据(例如):

@app.route('/index/')
def index():
    user_photo = slidephoto.query.filter_by(uid=5).all()

现在我想知道如何插入数据。我试过这个:

@app.route('/insert/')
def insert():
    act = slidephoto.query.insert().execute(uid='2016', photo='niloofar.jpg')
    return 'done'

但它不能满足我的需要。我该怎么办?

我已阅读并测试了其他答案和解决方案,但其中没有一个对我的脚本有用。

================ update ================

如果它有帮助我就不会...但这里是app.py中的所有导入和配置:

import os, sys
from niloofar import *
from flask import Flask, request, url_for, render_template, make_response, redirect
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://myusername:mypassword@localhost/mydbname'
db = SQLAlchemy(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

3 个答案:

答案 0 :(得分:1)

我希望我的回答可以帮助您解决问题。

from sqlalchemy import create_engine, MetaData, Table, insert
# I have tested this using my local postgres db.
engine = create_engine('postgresql://localhost/db', convert_unicode=True)
metadata = MetaData(bind=engine)
con = engine.connect()
act = insert(slidephoto).values(uid='2016', photo='niloofer.jpg')
con.execute(act)

答案 1 :(得分:0)

我编写了一个插入工作的简单演示,您可以将其作为参考:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()


class FirstTest(db.Model):
    __tablename__ = "first_test"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)

    def __init__(self, name):
        self.name = name


# Fill your db info here
mysql_info = {
    "user": "",
    "pwd": "",
    "host": "",
    "port": 3306,
    "db": "",
}

app = Flask(__name__)

app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
# Here I use pymysql
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://{0}:{1}@{2}:{3}/{4}".format(
    mysql_info["user"], mysql_info["pwd"], mysql_info["host"],
    mysql_info["port"], mysql_info["db"])

db.__init__(app)


@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    with app.test_request_context("/"):
        record = FirstTest("test")
        db.session.add(record)
        db.session.commit()

答案 2 :(得分:0)

您应该使用查询作为方法。喜欢' query()'