Model: qwen2.5-coder:32b
python function that takes URL to a CSV file and path to a SQLite database, fetches the CSV with the standard library, creates a table with the right columns and inserts the data
Certainly! Below is a Python function that accomplishes this task using only the standard library (urllib
for fetching the CSV, csv
for reading the CSV file, and sqlite3
for interacting with the SQLite database).
import csv
import sqlite3
from urllib import request
def fetch_csv_and_insert_to_sqlite(csv_url, db_path):
# Fetch the CSV from the URL
response = request.urlopen(csv_url)
reader = csv.reader(response.read().decode('utf-8').splitlines())
# Extract headers (column names) from the first row of the CSV
headers = next(reader)
# Create a connection to the SQLite database (will be created if it doesn't exist)
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Generate the SQL statement for creating the table
columns_with_types = ', '.join([f'"{header}" TEXT' for header in headers])
create_table_query = f'CREATE TABLE IF NOT EXISTS data ({columns_with_types})'
cursor.execute(create_table_query)
# Prepare the SQL insert query
placeholders = ', '.join(['?' for _ in headers])
insert_query = f'INSERT INTO data VALUES ({placeholders})'
# Insert each row from the CSV into the SQLite table
cursor.executemany(insert_query, reader)
# Commit changes and close the connection
conn.commit()
conn.close()
# Example usage:
csv_url = 'https://example.com/path/to/your/file.csv'
db_path = '/path/to/your/database.db'
fetch_csv_and_insert_to_sqlite(csv_url, db_path)
-
Fetching CSV from URL: The
urllib.request.urlopen
function is used to fetch the CSV file from the provided URL. -
Reading CSV Data: The CSV data is decoded and split into lines using
splitlines()
. Acsv.reader
object is created to read the CSV data. -
Extracting Headers: The first row of the CSV (headers) is extracted and used to determine the column names for the SQLite table.
-
Creating Table in SQLite: A SQL statement is generated to create a new table named
data
with columns corresponding to the headers from the CSV file. All columns are defined asTEXT
type for simplicity. The table is created only if it does not already exist (CREATE TABLE IF NOT EXISTS
). -
Inserting Data into SQLite: The CSV data (excluding the header row) is inserted into the newly created table using
executemany
, which executes an SQL statement with parameters. -
Committing Changes and Closing Connection: All changes are committed to the database, and the connection is closed.
- This script assumes all data can be stored as text (
TEXT
). You might need to modify the column types if your data includes integers or other non-text data types. - The table name
data
is hardcoded. If you want a different table name, you can pass it as an additional parameter to the function. - Error handling (e.g., network issues, invalid CSV format) is not included in this script for simplicity. You might want to add error handling depending on your requirements.
Feel free to modify the code according to your specific needs!
This gave me an annoying SSL error which I fixed myself like this:
Then I ran this:
Which worked, I got a database with a schema like this:
And this many rows: