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

问题描述 投票:0回答:1

我使用flask创建了一个应用,它从用户那里获取输入,并将输入保存到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:'Database'对象没有属性'cur')我是新数据库和python。所以我不知道如何解决它。我该如何解决该问题。谢谢。

python-3.x database postgresql psycopg2
1个回答
0
投票

错误是由于未正确使用Class而导致的。不需要global,因为变量可以在类构造函数中初始化。

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

注意:我将querycreate方法重构为execute_query。同样,仍然可以改进方法以进行正确的错误处理。添加try and catch块就足够了。

# 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)
© www.soinside.com 2019 - 2024. All rights reserved.