Home > Backend Development > Python Tutorial > How to Import a CSV File into an SQLite3 Database Table with Python?

How to Import a CSV File into an SQLite3 Database Table with Python?

Barbara Streisand
Release: 2024-11-28 04:34:09
Original
957 people have browsed it

How to Import a CSV File into an SQLite3 Database Table with Python?

Converting a CSV File into an SQLite3 Database Table with Python

Importing a CSV file directly into an SQLite3 database table is not possible using the ".import" command. However, this can be achieved using the following steps:

Establish a Database Connection

Use the sqlite3 module to establish a connection to a database (either an in-memory database or a file-based database):

import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()
Copy after login

Create the Target Table

Create the table that will hold the imported data using the "CREATE TABLE" statement, specifying the column names and data types:

cur.execute("CREATE TABLE t (col1, col2);")
Copy after login

Read the CSV File

Open the CSV file and read its contents using a CSV reader. If the column names are specified in the first line of the file, you can use csv.DictReader to map them to a dictionary:

with open('data.csv', 'r') as fin:
    dr = csv.DictReader(fin)
Copy after login

Convert CSV Data to Lists

Convert the dictionary rows from the CSV reader into a list of tuples:

to_db = [(i['col1'], i['col2']) for i in dr]
Copy after login

Insert Data into the Table

Use the executemany() method on the cursor object to insert the list of tuples into the target table:

cur.executemany("INSERT INTO t (col1, col2) VALUES (?, ?);", to_db)
Copy after login

Commit Changes

Commit the changes to the database to make them persistent:

con.commit()
Copy after login

Close the Connection

Finally, close the database connection:

con.close()
Copy after login

The above is the detailed content of How to Import a CSV File into an SQLite3 Database Table with Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template