0

I'm following this CS50 tutorial on SQL:

They're writing a program to iterate through rows in a csv file to insert data into a a table column using sqlite3, python and sql placeholders.

Obviously their code works with no problem but since they are using a CS50 library and I need to achieve this using sqlite3 in python, I'm struggling on line 22 (using cur.executemany() inserts single characters instead of words while cur.execute() gives me this error: ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 10 supplied.).

# PROGRAM TO AUTOMATICALLY INSERT TV SHOWS title INTO shows TABLE FROM CSV FILE IN PYTHON

# import sqlite3, csv, create sqlite3 connection
import sqlite3
import csv
con = sqlite3.connect('shows.db')
cur = con.cursor()

# execute sql statement
cur.execute("CREATE TABLE shows (id INTEGER, title TEXT, PRIMARY KEY(id))")

# Open CSV file
with open("favorite_tv_shows.csv", "r") as file:
    # Create DictReader
    reader = csv.DictReader(file)
    # Iterate over CSV file
    for row in reader:
        # Canoncalize title
        title = row["title"].strip().upper()

        # Insert title, using ? PLACEHOLDER
        id = cur.executemany("INSERT INTO shows (title) VALUES(?)", title)
        # cur.execute() GIVES ME ERROR

# save, close conncetion
con.commit()
con.close()

CSV file example, "favorite_tv_shows.csv":

Timestamp,title,genres 10/19/2020 13:34:57,The Office,Comedy 10/19/2020 13:35:14,Friends,Comedy

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Chris Faux
  • 145
  • 9
  • 2
    `cur.execute("INSERT INTO shows (title) VALUES(?)", (title,))` is probably what you want. Note that `execute` expects a _tuple_ of values, even if there is only one. Likewise, `executemany` expects a _list of tuples_, for example `cur.executemany("INSERT INTO shows (title) VALUES(?)", [(title,)])`. – snakecharmerb Apr 25 '21 at 15:38
  • stackoverflow doesn't show line numbers. Which line is 22 ? – furas Apr 25 '21 at 23:48
  • Line 22: id = cur.executemany("INSERT INTO shows (title) VALUES(?)", title) – Chris Faux Apr 27 '21 at 03:44
  • thanks snakecharmerb, this answer my question. – Chris Faux Apr 27 '21 at 03:50

0 Answers0