To write data to a PostgreSQL database using Python, you can use the psycopg2
library. Here’s an example code
import psycopg2 # Connect to the PostgreSQL database conn = psycopg2.connect( host='your_host', user='your_user', password='your_password', database='your_database' ) # Create a cursor object cur = conn.cursor() # Define the data you want to insert data = ('John Doe', 30, '[email protected]') # Execute an INSERT query query = "INSERT INTO your_table (name, age, email) VALUES (%s, %s, %s)" cur.execute(query, data) # Commit the changes conn.commit() # Close the cursor and connection cur.close() conn.close()
In this example, replace 'your_host'
, 'your_user'
, 'your_password'
, and 'your_database'
with the actual connection details for your PostgreSQL database.
The code establishes a connection to the PostgreSQL database using the specified host, username, password, and database name. It then creates a cursor object to execute SQL queries.
The example defines the data you want to insert into the table as a tuple (data
). The %s
placeholders in the INSERT query represent the values to be inserted.
The code executes the INSERT query using the execute()
method, passing the query and the data tuple as parameters.
Finally, the changes are committed to the database using conn.commit()
, and the cursor and connection are closed to release the resources.
Make sure to have the psycopg2
library installed before running this code. You can install it using pip:
pip install psycopg2
Remember to handle any exceptions that may occur during the database connection or query execution for proper error handling.