SQL table 名称的语法错误

SQL syntax error on table name

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

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

这可能不是执行此操作的正确方法,我在 google 上遇到问题后正在寻求指导。 这是 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';");

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