开发者

Database connection in Python

I am building a flask application having multiple tables connected to a database. I have defined the connections as below,

connection = psycopg2.connect(host=config['CCM']['host'],
                              database=config['CCM']['database'],
                              port=config['CCM']['port'],
                              user=config['CCM']['user'],
                              password=config['CCM']['password'])

def function1():
    cursor = connection.cursor()
    cursor.execute('select * from table1')
    data = cursor.fetchall()
    return data

def function2():
    cursor = connection.cursor()
    cursor.execute('select * from table2')
    data = cursor.fetchall()
    return data

def function3():
    cursor = connection.cursor()
    cursor.execute('select * from table3')
    data = cursor.fetchall()
    return data

Similarly I have multiple python functions which connects to the database. Wanted to understand am I doing the database connection in a right way, defining the connection once and creat开发者_如何学Cing the cursor and connecting multiple times. Or do I need to create connection inside every function. Also I wanted to understand the right way of closing the cursor


Defining the database connection once is fine. After creating a cursor make sure to also close it with cursor.close() or use a context manager to close it automatically:

def function1():
    with connection.cursor() as cursor:
        cursor.execute('select * from table1')
        data = cursor.fetchall()
    return data

The standard tool to work with databases in Flask is to use Flask-SQLAlchemy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜