PYTHON 3 and SQLite 3, please help and explain. to table: This function takes a
ID: 3744235 • Letter: P
Question
PYTHON 3 and SQLite 3, please help and explain.
to table: This function takes a csv filename, an SQLite filename, and a table name with default value "new1". It adds a new table with the specified name to the db that has the information from the csv file in it. The first row of the csv file contains the column names. All columns are TEXT type. The first column is the primary key. I recommend using Python's csv module so you don't have to parse the rows of the csv file yourself. HINT: look into using qmark notation with the sqlite3 .execute() method, ex: c.exectue('INSERT INTO VALUES (?, ?)', (varl, var2))Explanation / Answer
here is your function : ------------------>>>>>>>>>>>>>
import csv
import sqlite3
def to_table(cfl,Tname="new1"):
c = sqlite3.connect('dbname')#give dbname here
with open(cfl,'rt') as cfile:
rd = csv.reader(cfile,delimiter=',',quotechar='|')
i = 1
for row in rd:
if i == 1:
qr = 'CREATE TABLE '+Tname+'('
for col in row:
qr += col+' VARCHAR (30) ,'
qr += 'PRIMARY KEY ('+row[0]+') );'
c.execute(qr)
i = 2
else:
qr = 'INSERT INTO '+Tname+' VALUES (?'
for i in range(len(row) - 1):
qr += ' ,?'
qr += ') '
c.execute(qr,row)
c.commit()
c.close()
to_table("fgf.csv",'Userssssss')
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.