Ask Your Question
1

How can I use a variable to insert multiple rows from JSON data into PostgreSQL?

asked 2023-06-14 16:13:22 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-14 16:41:02 +0000

lalupa gravatar image

You can use a loop to iterate through the JSON data and insert each row into the PostgreSQL database. Here's an example of how you can do this in Python using the psycopg2 library:

import psycopg2
import json

# Connect to the PostgreSQL database
conn = psycopg2.connect(
    dbname="database_name",
    user="username",
    password="password",
    host="localhost"
)

# Get the JSON data and parse it into a list of dictionaries
json_data = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]'
data = json.loads(json_data)

# Define the SQL statement for inserting a single row
sql = "INSERT INTO table_name (name, age) VALUES (%s, %s)"

# Loop through the list of dictionaries and insert each row into the database
with conn.cursor() as cur:
    for row in data:
        values = (row["name"], row["age"])
        cur.execute(sql, values)
    conn.commit()

# Close the database connection
conn.close()

In this example, we first establish a connection to the PostgreSQL database using the psycopg2 library. We then define a JSON string with sample data and parse it into a list of dictionaries using the json.loads() method.

We define an SQL statement for inserting a single row into a table and use a loop to iterate through the list of dictionaries. For each dictionary, we extract the name and age values and insert them into the table using the execute() method of the psycopg2 cursor.

Finally, we commit the changes to the database and close the connection. Note that you'll need to replace "databasename", "username", "password", "host", "tablename" with your own values.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-14 16:13:22 +0000

Seen: 13 times

Last updated: Jun 14 '23