使用 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中文网其他相关文章!