PostgreSQL - Insert Data Into a Table using Python

PostgreSQL - Insert Data Into a Table using Python

To insert data into a PostgreSQL table using Python, you can utilize the psycopg2 library, which is a popular PostgreSQL adapter for Python. Below is a step-by-step guide:

1. Install psycopg2

You can install psycopg2 using pip:

pip install psycopg2 

If you run into any issues, you can try installing the binary version:

pip install psycopg2-binary 

2. Connect to the Database

Establish a connection to the PostgreSQL database:

import psycopg2 # Database connection parameters dbname = 'your_database_name' user = 'your_username' password = 'your_password' host = 'localhost' # or another host if your db isn't on localhost # Connect to the database conn = psycopg2.connect(dbname=dbname, user=user, password=password, host=host) 

3. Insert Data into a Table

# Create a cursor object cur = conn.cursor() # Define the SQL query for insertion query = """ INSERT INTO your_table_name (column1, column2, column3) VALUES (%s, %s, %s) """ # Data to be inserted data = ("value1", "value2", "value3") # Execute the SQL query cur.execute(query, data) # Commit the transaction conn.commit() 

If you have multiple rows of data to insert:

data_rows = [ ("value1", "value2", "value3"), ("value4", "value5", "value6"), # ... add more rows as needed ] cur.executemany(query, data_rows) conn.commit() 

4. Close the Connection

Always ensure you close the cursor and connection after you're done:

cur.close() conn.close() 

That's it! Using this approach, you can insert data into a PostgreSQL table from a Python script. Remember to handle exceptions and errors for robustness (e.g., using try-except blocks), especially when deploying in production environments.


More Tags

data-conversion transpiler terraform-provider-azure mingw32 ios9 rx-java reusability android-nested-fragment os.system android-screen-support

More Programming Guides

Other Guides

More Programming Examples