使用Python 將CSV 檔案匯入SQLite 資料庫
在Python 中,利用sqlite3模組讓開發人員能夠輕鬆匯入將CSV 檔案中的資料匯入sqlite3 資料庫表中。雖然“.import”命令可能無法直接應用,但替代方法提供了完成此任務的簡單方法。
範例程式碼:
說明導入過程,考慮以下Python程式碼:
import csv, sqlite3 # Connect to the database (in-memory or file) and create a cursor con = sqlite3.connect(":memory:") # change to 'sqlite:///your_filename.db' cur = con.cursor() cur.execute("CREATE TABLE t (col1, col2);") # use your column names here # Open the CSV file for reading with open('data.csv','r') as fin: # Create a DictReader object to read data from the CSV file dr = csv.DictReader(fin) # comma is default delimiter # Convert CSV data into a list of tuples for database insertion to_db = [(i['col1'], i['col2']) for i in dr] # Execute the insert query using executemany to efficiently import data cur.executemany("INSERT INTO t (col1, col2) VALUES (?, ?);", to_db) # Commit changes to the database con.commit() # Close the connection and cursor con.close()
說明:
以上是如何使用 Python 將 CSV 檔案匯入 SQLite 資料庫?的詳細內容。更多資訊請關注PHP中文網其他相關文章!