sqlalchemy插入数据不起作用 [英] sqlalchemy insert data does not work
本文介绍了sqlalchemy插入数据不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在models.py中,我定义了:
In models.py I have define:
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) + "}"
我选择这样的数据(例如):
I select data like this (for example):
@app.route('/index/')
def index():
user_photo = slidephoto.query.filter_by(uid=5).all()
现在我想知道如何插入数据。我尝试过这个:
Now I want to know how to insert data. I tried this:
@app.route('/insert/')
def insert():
act = slidephoto.query.insert().execute(uid='2016', photo='niloofar.jpg')
return 'done'
但是它不能满足我的需求。我该怎么办?
But it does not do what I need. What should I do?
我已经阅读并测试了其他答案和解决方案,但是这些答案和解决方案都不适合我的脚本。
I have read and tested other answers and solutions, but none of them was useful for my script.
================更新==============
================ update ================
我不是没有帮助的...但是这里是app.py中的所有导入和配置:
I don't no if it helps... but here is all imports and configs in 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
推荐答案
我希望我的回答可以帮助您解决问题。
I hope that my answer will help you solving the problem.
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)
这篇关于sqlalchemy插入数据不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文