Here’s a sample Python code to write data to a SQLite database from a CSV file
import sqlite3 import csv # Open the CSV file and read its contents with open('data.csv', 'r') as file: csv_reader = csv.reader(file) # Connect to the SQLite database conn = sqlite3.connect('mydatabase.db') cursor = conn.cursor() # Create a table in the database to hold the data cursor.execute('''CREATE TABLE IF NOT EXISTS mytable (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, address TEXT);''') # Insert the data into the database for row in csv_reader: cursor.execute('''INSERT INTO mytable (name, age, address) VALUES (?, ?, ?)''', (row[0], row[1], row[2])) # Commit the changes and close the database connection conn.commit() conn.close()
This code assumes that the CSV file named data.csv
is located in the same directory as the Python script. It also assumes that the SQLite database file named mydatabase.db
already exists in the same directory. The code reads the CSV file and inserts each row of data into a table named mytable
in the database. The table has three columns: name
, age
, and address
. The first row of the CSV file is assumed to contain the column headers and is skipped during the insertion process.