PSYCOPG2 method and example of connecting databases in Python
Use the PSYCOPG2 library to connect the database method and example in Python
Overview:
PSYCOPG2 is a library that is popular in Python to connect and operate PostgresQL database.In this article, we will introduce how to use PsycopG2 to connect the database in Python.
Install psycopg2:
Before the beginning, we need to install the PsycopG2 library.We can use the following command to install it in the Python environment:
pip install psycopg2
Connect to the database:
To be connected to the PostgreSQL database, we need to provide host names, database names, user names and passwords.We can use the following code to create a database connection object:
import psycopg2
# Configure database connection parameters
dbname = 'your_database_name'
user = 'your_username'
password = 'your_password'
host = 'your_host'
port = 'YOUR_PORT' # defaults to 5432
# Create database connection objects
connection = psycopg2.connect(dbname=dbname, user=user, password=password, host=host, port=port)
In the above code, we use the Connect function of the PSYCOPG2 module to create a connection object to the designated database.We pass the database connection parameters such as DBNAME, User, Password, Host, and Port.
Execute SQL query:
Once we successfully establish a database connection, we can use the connection object to create a cursor object to perform SQL query and obtain the query results.The following is an example:
# Create a cursor object
cursor = connection.cursor()
# 查 SQL query
cursor.execute("SELECT * FROM your_table_name")
# Get the query results
result = cursor.fetchall()
# Print results
for row in result:
print(row)
In the above code, we use the Cursor method of the connection object to create a cursor object.We then perform a SQL query using the Execute method of the cursor object.Finally, we use the fetchall method to obtain the query result and print the results of each line with a cycle.
Turn off the database connection:
When we complete the operation of the database, we should close the database connection.We can use the following code to close the connection:
# Close the cursor object
cursor.close()
# Close database connection
connection.close()
In the above code, we use the Close method of the cursor object to close the cursor object and use the close method of the connected object to close the database connection.
Summarize:
In this article, we learned how to connect to the PostgreSQL database in Python in Python.We introduced the steps of creating database connection objects, executing SQL queries and closing connections.With PSYCOPG2, we can easily connect and operate the PostgreSQL database.