trying to import csv file into postgresql database through python3

Viewed 335

This is my cs50w project here i'm trying to import books.csv file into the postgresql database but i'm getting some errors, i think i'm having some problem with my script can someone correct it...

import psycopg2
import csv

#For connecting to the database
conn = psycopg2.connect("host=hostname_here port=5432 dbname=dbname_here user=username_here password=pass_here")
cur = conn.cursor()

#importing csv file
with open('books.csv', 'r') as f:
    reader = csv.reader(f)
next(reader)

for row in reader:
    cur.execute("INSERT INTO book VALUES (%s, %s, %s, %s)",
                row
                )
    conn.commit()


Traceback (most recent call last):
  File "import.py", line 15, in <module>
  row
psycopg2.errors.SyntaxError: INSERT has more expressions than target      columns
LINE 1: INSERT INTO book VALUES ('0380795272', 'Krondor: The Betraya...

sample of csv file : sample of csv file :

2 Answers

INSERT has more expressions than target columns.

You are trying to insert a row with 4 values in a table that has less than 4 columns.

However, if the table indeed has 4 columns, you need to review your data source (books.cvs.) The source data may have some single quotes or commas. Either remove the problematic data from the file or modify your program to handle the data correctly.

Problem solved in my postgres table i set isbn to integer but i didnt see the alphabets with it now i changed isbn column to varchar and problem is solved

Related