如何使用psycopg2将数据插入Postgres数据库

我使用烧瓶创建了一个应用程序,它从用户那里获取输入并将输入保存到Postgres数据库中,这里是代码:

    from flask import Flask, request, render_template, jsonify
    import psycopg2 as pg2
    import exquixdb

    app = Flask(__name__)


    @app.route('/questions', methods=["POST"])
    def post_question():
        request_data = request.json

        table = ("INSERT INTO question(id, question) VALUES(%s,%s)", (1003, str(request_data['question'])))
        exquixdb.db.create(table)
        app.logger.info("adding questions")



        return "question saved"


    if __name__ == '__main__':
        app.run(debug=True, port=8989)

我创建了一个数据库模块,代码为:

# Module exquizdb.py
import psycopg2 as pg2


class Database():
    def db_connect(self, db="exquizdb", user="jim", pas="password", port=5433):
        global conn
        self.conn = pg2.connect(database=db, user=user, password=pas, port=port)
        global cur
        self.cur = self.conn.cursor()

    def close(self):
        self.cur.close()
        self.conn.close()

    def query(self, query):
        self.cur.execute(query)
        self.close()

    def create(self, table):
        self.cur.execute(table)
        self.conn.commit()
        self.close()


db = Database()

table = ("INSERT INTO question(id, question) VALUES(%s,%s)", (1003, 'Test'))

db.create(table)

因此,当我运行代码时,我得到了(AttributeError:“数据库”对象没有属性“ cur”),我是新数据库和python。所以我不知道如何解决它。我该如何解决该问题。谢谢。

评论
独唱情歌
独唱情歌

The error is as a result of not making proper use of Class. The global is not needed as the variables could have been initiated in the class constructor.

同样,可以将create和query方法定义为一个。在每个查询之后关闭连接意味着您必须在运行新查询之前创建一个新连接。

NOTE: I refactored the query and create method as execute_query. Also the methods can still be improved on for proper error handling. Adding a try and catch block can suffice.

# Module exquizdb.py
import psycopg2 as pg2


class Database:
  def __init__(self, db, username, password, port):
    self.db = db
    self.username = username
    self.password = password
    self.port = port
    self.cur = None
    self.conn = None

  def connect(self):
    self.conn = pg2.connect(database=self.db, user=self.user, password=self.password, port=self.port)
    self.cur = self.conn.cursor()

  def execute_query(self, query):
    self.cur.execute(query)
    self.conn.commit()

  def close(self):
    self.cur.close()
    self.conn.close()

db = Database(db="exquizdb", user="jim", pas="password", port=5433)

db.connect()
    from flask import Flask, request, render_template, jsonify
    import psycopg2 as pg2
    from exquixdb import db

    app = Flask(__name__)


    @app.route('/questions', methods=["POST"])
    def post_question():
        request_data = request.json

        table = ("INSERT INTO question(id, question) VALUES(%s,%s)", (1003, str(request_data['question'])))
        db.execute_query(table)
        app.logger.info("adding questions")


        return "question saved"


    if __name__ == '__main__':
        app.run(debug=True, port=8989)
点赞
评论