I'm trying to create an SQL table from CSV file using Python sqlite3 library. That's the code I wrote:
import csv
import sqlite3
csv_file = 'path/to/file.csv'
db = sqlite3.connect('clients.db')
db.execute('''CREATE TABLE main(
ID INT PRIMARY KEY NOT NULL,
name VARCHAR,
email VARCHAR,
address VARCHAR);''')
# That part is only for getting the number of rows in the table
with open(csv_file, 'r') as csv_table:
reader = csv.DictReader(csv_table, delimiter=';')
rows = sum(1 for r in reader)
# Here I'm reading the table
with open(csv_file, 'r') as csv_table:
reader = csv.DictReader(csv_table, delimiter=';')
for i, row in enumerate(reader):
db.execute('''INSERT INTO main VALUES
('{idn}', '{name}', '{email}', '{add}');'''.format(idn=i,
name=row['name'],
email=row['email'],
add=row['address']))
print('{}/{}:\t{}'.format(i+1, rows, row))
db.commit()
db.close()
After I've run this code I tried to access the table with sqlite3 but I got the error message: "Error: no such table: main" anytime I've send a query regarding 'main' table.
I've tried to read the table with Python and it works fine:
import sqlite3
db = sqlite3.connect('clients.db')
rows = db.execute('SELECT * FROM main;')
for r in rows:
print(r)
I'm running this script from the same directory that I'm running SQLite3.
I'm using Python 3.6 and my OS is Ubuntu 16.04.6 LTS.