Search code examples
pythonpostgresqlpycharmconnectionpsycopg2

How to call PostgreSQL connection once using PyCharm?


I made a project using PyCharm and QT Designer and the database I used is PostgreSQL, all forms that is connected to database has the following codes:

*try:
connection = psycopg2.connect(user="postgres",
                              password="admin",
                              host="127.0.0.1",
                              port="5432",
                              dbname="database")*

Is there any way(s) to call the connection once for all forms?


Solution

  • As an option, you could put the db connection code in a module and import that module in the forms

    connection.py

    connection = psycopg2.connect(user="postgres",
                              password="admin",
                              host="127.0.0.1",
                              port="5432",
                              dbname="database")
    

    form1.py

     from yourproject.connection import connection
     cursor = connection.cursor()
     ...