gpt4 book ai didi

python - 表名 SQL 语法错误

转载 作者:行者123 更新时间:2023-11-29 10:05:25 26 4
gpt4 key购买 nike

我刚刚完成了有关阻止论坛数据库中的垃圾邮件的部分,现在是时候清理它们了。

目标是使用update语句更新数据库记录并删除标记为垃圾邮件的帖子。在摸不着头脑并从在线讲师那里收到模糊的提示和指示(这是针对在线类(class))后,我遇到了一个错误。

这可能不是正确的方法,我在谷歌上没有运气后正在寻找指导。以下是 forumdb.py 的片段:

# "Database code" for the DB Forum.

import bleach
import psycopg2
import datetime

DBNAME = "forum"

def get_posts():
"""Return all posts from the 'database', most recent first."""
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
UPDATE posts
SET content = 'cheese'
WHERE content like 'spam' ;
c.execute("select content, time from posts order by time desc")
return c.fetchall()
db.close()

def add_post(content):
"""Add a post to the 'database' with the current timestamp."""
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
clean_cont = bleach.clean(content)
c.execute("insert into posts values (%s)", (clean_cont,))
db.commit()
db.close()

这是我得到的错误:

Traceback (most recent call last):
File "forum.py", line 7, in <module>
from forumdb import get_posts, add_post
File "/vagrant/forum/forumdb.py", line 13
UPDATE posts
^
SyntaxError: invalid syntax

如果有帮助,这里是forum.py:

#!/usr/bin/env python3
#
# A buggy web service in need of a database.

from flask import Flask, request, redirect, url_for

from forumdb import get_posts, add_post

app = Flask(__name__)

# HTML template for the forum page
HTML_WRAP = '''\
<!DOCTYPE html>
<html>
<head>
<title>DB Forum</title>
<style>
h1, form { text-align: center; }
textarea { width: 400px; height: 100px; }
div.post { border: 1px solid #999;
padding: 10px 10px;
margin: 10px 20%%; }
hr.postbound { width: 50%%; }
em.date { color: #999 }
</style>
</head>
<body>
<h1>DB Forum</h1>
<form method=post>
<div><textarea id="content" name="content"></textarea></div>
<div><button id="go" type="submit">Post message</button></div>
</form>
<!-- post content will go here -->
%s
</body>
</html>
'''

# HTML template for an individual comment
POST = '''\
<div class=post><em class=date>%s</em><br>%s</div>
'''


@app.route('/', methods=['GET'])
def main():
'''Main page of the forum.'''
posts = "".join(POST % (date, text) for text, date in get_posts())
html = HTML_WRAP % posts
return html


@app.route('/', methods=['POST'])
def post():
'''New post submission.'''
message = request.form['content']
add_post(message)
return redirect(url_for('main'))


if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)

预先感谢任何有能力提供帮助的人!

最佳答案

您的查询

UPDATE posts
SET content = 'cheese'
WHERE content like 'spam' ;

超出范围。删除或将其放在 c.execute() 函数上,如下所示

c.execute("UPDATE posts SET content = 'cheese' WHERE content like 'spam';");

这就是您收到此错误的原因,希望它有所帮助。

关于python - 表名 SQL 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52013248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com