Simplify database (psycopg2) usage by creating a module

假装没事ソ 提交于 2019-12-06 01:25:45

Your main issue, is that each variable is limited to the function you wrote it in.
Unless otherwise declared like such:

def db_init():
    global conn
    conn = psycopg2....

A better approach would be to convert this into a class, a basic example would be:

import psycopg2

class MyDatabase():
    def __init__(self, db="mydb", user="postgres"):
        self.conn = psycopg2.connect(database=db, user=user)
        self.cur = self.conn.cursor()

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

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

db = MyDatabase()
db.query("SELECT * FROM table;")
db.close()

Now, the SELECT query won't do much since you're using cur.execute().
But i kept this on purpose to keep the code similar to what you wrote, you'll want to swap that out to return the values however if calling a query that is expected to return a value and so on.

Your approach that is focused on functions will have "namespace" issues where variables live in a local scope of that function and there for other functions can't normally access them.

Instead, class scoped variables can access its own variables and is there for not as limited out of the box.

You could make global variables and declare them as global in the functions, but I think as I mentioned in a comment:

You'd want to make this into a class. A database is a session based entity just as classes are session entities. Handle each connection as a living entity by class-abstracting it, otherwise cur and conn will become scoped variables and you need to work them into the global scope.

You could do it the way you want to - although I would consider using sqlalchemy or other module to handle those parts for you.

The code you pasted doesn't work because cursor is not defined in your other methods.

Consider doing it in one call - for example:

# Module core.py

import psycopg2

def execute_query(query):
    conn = psycopg2.connect(database="mydb", user="postgres")
    cur = conn.cursor()
    results = cur.execute(query)
    cur.close()
    conn.close()
    return results

Note that this is not optimal and if you are doing a lot of small queries killing connection for each one is not the best idea.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!