在PYTHON DB-API上使用Postgres插入INTO

时间:2017-11-04 04:21:59

标签: postgresql sql-insert python-db-api

我正在尝试使用postgreSQL和Python DB-API学习将后端添加到简单的Web应用程序。

运行应用程序时,如果forumdb中的函数 get_posts(),为什么会出错? python使用c. execute ("SELECT * FROM posts ORDER BY time;)而不是SELECT content, time FROM posts ORDER BY time;)

其次,任何人都可以解释为什么c.execute("INSERT INTO posts VALUES (content)")不起作用,我们必须在forumdb.py中的函数 add_post(content)中使用('%s') % content?< / p>

以下是forum.py

from flask import Flask, request, redirect, url_for

# Using a module called forumdb
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)

以下是forumdb.py

# "Database code" for the DB Forum.

import psycopg2
import datetime


def get_posts():
    con = psycopg2.connect(dbname="forum")
    c = con.cursor()
    """Return all posts from the 'database', most recent first."""
    c.execute("SELECT content, time FROM posts ORDER BY time;")
    return c.fetchall()
    con.close()


def add_post(content):
    con = psycopg2.connect(dbname="forum")
    c = con.cursor()
    """Add a post to the 'database' with the current timestamp."""
    c.execute("INSERT INTO posts VALUES ('%s')" % content)
    con.commit()
    con.close()

谢谢!

1 个答案:

答案 0 :(得分:0)

因为使用的是参数化查询,所以在查询中使用占位符作为参数,并在执行时提供参数值。

当我们要在SQL查询中使用变量时,需要为其使用占位符。

示例

function Node(value, parent) {
    let children = [];

    let self = {
        value: value,
        children: children, 

        // create and return a new node for the value
        add: value => {
            let child = Node(value, self);
            children.push(child);
            return child;
        },

        // remove this node from its parent, if it has one
        remove: () => {
            if (parent !== null && typeof parent !== 'undefined') {
                let indexInParent = parent.children.indexOf(self);
                if (indexInParent > -1) {
                    parent.children.splice(indexInParent, 1);
                }
            }
        },

        // return a plain object that has only data and contains no references to parents
        // JSON.stringify cannot handle circular references
        dataOnly: function () {
            return {
                value: value,
                children: children.map(c => c.dataOnly())
            }
        },

        // return a JSON string for this object
        makeJSON: () => JSON.stringify(self.dataOnly())
    };
    return self;
}


root = Node('lame');
child = root.add('child');
console.log(root.makeJSON());
// logs {"value":"lame","children":[{"value":"child","children":[]}]}