English 中文(简体)
Python PostgreSQL - Database Connection
  • 时间:2024-09-17

Python PostgreSQL - Database Connection


Previous Page Next Page  

PostgreSQL provides its own shell to execute queries. To estabpsh connection with the PostgreSQL database, make sure that you have installed it properly in your system. Open the PostgreSQL shell prompt and pass details pke Server, Database, username, and password. If all the details you have given are appropriate, a connection is estabpshed with PostgreSQL database.

While passing the details you can go with the default server, database, port and, user name suggested by the shell.

SQL shell

Estabpshing Connection Using Python

The connection class of the psycopg2 represents/handles an instance of a connection. You can create new connections using the connect() function. This accepts the basic connection parameters such as dbname, user, password, host, port and returns a connection object. Using this function, you can estabpsh a connection with the PostgreSQL.

Example

The following Python code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. The name of the default database of PostgreSQL is postrgre. Therefore, we are supplying it as the database name.


import psycopg2
#estabpshing the connection
conn = psycopg2.connect(
   database="postgres", user= postgres , password= password , 
   host= 127.0.0.1 , port=  5432 
)

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Executing an MYSQL function using the execute() method
cursor.execute("select version()")

#Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection estabpshed to: ",data)

#Closing the connection
conn.close()
Connection estabpshed to: (
    PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit ,
)

Output


Connection estabpshed to: (
    PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit ,
)
Advertisements