I am trying to insert data into a PostgreSQL database table using Python. I don't see any syntax errors but, for some reason, my data isn't getting inserted into the database.
conn = psycopg2.connect(connection) cursor = conn.cursor() items = pickle.load(open(pickle_file,"rb")) for item in items: city = item[0] price = item[1] info = item[2] query = "INSERT INTO items (info, city, price) VALUES (%s, %s, %s);" data = (info, city, price) cursor.execute(query, data)
To establish connection with the PostgreSQL database, make sure that you have installed it properly in your system. Open the PostgreSQL shell prompt and pass details like Server, Database, username, and password. If all the details you have given are appropriate, a connection is established with PostgreSQL database.
To insert character data, you enclose it in single quotes (') for example 'PostgreSQL Tutorial' . If you omit required columns in the INSERT statement, PostgreSQL will issue an error. In case you omit an optional column, PostgreSQL will use the column default value for insert.
In order to connect to a PostgreSQL database instance from your Python script, you need to use a database connector library. In Python, you have several options that you can choose from. Some libraries that are written in pure Python include pg8000 and py-postgresql.
First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2. connect() method. before importing a CSV file we need to create a table. In the example below, we created a table by executing the “create table” SQL command using the cursor.
You have to commit the transaction.
conn.commit()
If there's no reason to think the transaction will fail, it's faster to commit after the for loop finishes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With