0

Write a function named "csv_to_db" that takes a string as a parameter representing the name of a csv file and doesn't return a value. There is a database saved in a file named "port.db" containing a table named "introduce" with columns "luck", "reportedly", and "isolate". Read the csv file with the name equal to the input string and add each row of this file as a record in the table. Each row in the csv file will contain 3 strings as its values which should be used as the values for the three columns in the table.

import sqlite3
import csv
def csv_to_db(string):
    conn = sqlite3.connect('port.db')
    with open(string, 'r') as f:
        reader = csv.reader(f)
        for row in reader:
            c = conn.cursor()
            insert = c.executemany('INSERT INTO introduce VALUES (?, ?, ?)', row)
            conn.commit()

Here is my attempt at the question; getting error: The current statement uses 3, and there are 10 supplied. How can I fix this?

  • No need to write any code: https://www.sqlite.org/cli.html#csv_import – Shawn Nov 24 '18 at 20:40
  • What do you mean? –  Nov 24 '18 at 20:56
  • Possible duplicate of [Importing a CSV file into a sqlite3 database table using Python](https://stackoverflow.com/questions/2887878/importing-a-csv-file-into-a-sqlite3-database-table-using-python) – stovfl Nov 24 '18 at 21:00
  • Read the link. The sqlite3 shell can import CSV files into tables for you. No need to write your own code for a trivial case like this. `sqlite3 -csv port.db '.import your_file.csv introduce'` – Shawn Nov 24 '18 at 21:10

1 Answers1

0
import sqlite3
import csv
def csv_to_db(str):
    connection = sqlite3.connect('port.db')
    with open(str, 'r') as f:
        reader = csv.reader(f)
        for row in reader:
            c = connection.cursor()
            c.execute('INSERT INTO introduce VALUES(?,?,?)', (row[0],row[1],row[2]))
    connection.commit()