我有以下代码将数据(detector_id,video_id,score)插入表得分(如果它不存在),如果它存在,则将得分添加到其现有值:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = SQLALCHEMY_DATABASE_URI
db = SQLAlchemy(app)
query = "DO $$ BEGIN UPDATE "+table_score+" SET score = score + \'"+ concept_score +"\' " + \
"WHERE detector_id = \'"+ detector_id +"\' AND video_id = \'"+video_id+"\'; " + \
"IF NOT FOUND THEN INSERT INTO "+table_score+" VALUES (\'"+detector_id+"\', \'"+video_id+"\', "+concept_score+"); " + \
"END IF; END $$;"
result = db.engine.execute(query)
这相当于以下内容,当我在pgAdmin中执行它时可以正常工作:
DO $$ BEGIN
UPDATE score SET score = score + SCORE_VALUE
WHERE detector_id = 'DETECTOR_ID' AND video_id = 'VIDEO_ID';
IF NOT FOUND THEN
INSERT INTO score VALUES ('DETECTOR_ID', 'VIDEO_ID', SCORE_VALUE);
END IF;
END $$
但是,如果我尝试执行Python代码,它不会添加任何内容。我也没有收到任何错误消息。其他查询工作正常,所以它不是我的数据库连接的问题。当我尝试输出list(result)
时,它会返回:This result object does not return rows.
如果我执行print query
,并在pgAdmin中运行该字符串,则可以正常工作。但是,db.engine.execute(query)
运行它不会。其他查询(例如SELECT * FROM score s WHERE s.detector_id ='DETECTOR_ID';
)可以与db.engine.execute(query)
一起使用。这是否与DO $$..
声明有关?
以下工作正常,但似乎过分:
query = "SELECT * FROM "+table_score+" s WHERE s.detector_id = \'"+ detector_id +"\' AND s.video_id = \'"+video_id+"\';"
result = db.engine.execute(query)
if len(list(result)) > 0:
query = "UPDATE "+table_score+" SET score = score + \'"+ concept_score +"\' WHERE detector_id = \'"+ detector_id +"\' AND video_id = \'"+video_id+"\';"
else:
query = "INSERT INTO "+table_score+" VALUES (\'"+detector_id+"\', \'"+video_id+"\', "+concept_score+");"
result = db.engine.execute(query)