Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using INSERT with a PostgreSQL Database using Python

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) 
like image 534
Ching Chong Avatar asked Jan 31 '12 06:01

Ching Chong


People also ask

How do I connect to a Postgres database using Python?

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.

How create PostgreSQL insert?

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.

Can we connect PostgreSQL to Python?

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.

How do I import a CSV file into PostgreSQL using Python?

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.


1 Answers

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.

like image 104
GuillaumeDufay Avatar answered Oct 05 '22 23:10

GuillaumeDufay