fbpx

Insert JSON Data File into PostgreSQL using Python Script

the psycopg2 library to connect to the database and execute an INSERT statement. Here is an example:

				
					import json
import psycopg2

# read JSON data from file
with open('data.json') as f:
    data = json.load(f)

# connect to the database
conn = psycopg2.connect(host="localhost", database="mydb", user="user", password="pass")

# create a cursor
cur = conn.cursor()

# execute the INSERT statement
cur.execute("INSERT INTO table_name (name, email, city) VALUES (%s, %s, %s)", (data["name"], data["email"], data["city"]))

# commit the changes to the database
conn.commit()

# close the cursor and connection
cur.close()
conn.close()

				
			

This code reads the JSON data from a file named “data.json”, and then uses the psycopg2 library to connect to a Postgres database. A cursor is used to execute an INSERT statement with the JSON data as the values. The changes are then committed to the database and the cursor and connection are closed.

Note that this is just an example, and you will need to modify the code to match the specific structure of your database and JSON data. You may also want to add error handling and additional functionality as needed. For example, you could read multiple JSON files or insert multiple records in a loop.

Share:

Facebook
Twitter
Pinterest
LinkedIn

Social Media

Most Popular

Get The Latest Updates

Subscribe To Our Weekly Newsletter

No spam, notifications only about new products, updates.

Categories