import csv
import sqlite3
 
def create_connection(db_file):
    """创建到SQLite数据库的连接"""
    conn = None
    try:
        conn = sqlite3.connect(db_file)
    except sqlite3.Error as e:
        print(e)
    return conn
 
def csv_to_sqlite(csv_file, sqlite_file, table_name):
    """将CSV文件转换为SQLite数据库的表"""
    conn = create_connection(sqlite_file)
    if conn is not None:
        # 使用`execute()`方法执行SQL语句
        cur = conn.cursor()
        try:
            cur.execute(f"DROP TABLE IF EXISTS {table_name}")
            cur.execute(f"""CREATE TABLE {table_name} (
                              id INTEGER PRIMARY KEY,
                              name TEXT,
                              value REAL
                          )""")
            with open(csv_file, 'r') as f:
                reader = csv.DictReader(f)
                to_db = [(i[1], i[2]) for i in reader]
                cur.executemany(f"INSERT INTO {table_name} (name, value) VALUES (?, ?)", to_db)
            conn.commit()
        except sqlite3.Error as e:
            print(e)
        finally:
            cur.close()
            conn.close()
 
# 使用函数转换CSV到SQLite
csv_to_sqlite('input.csv', 'output.db', 'my_table')这段代码首先定义了创建SQLite数据库连接的函数create_connection,然后定义了csv_to_sqlite函数,该函数接受CSV文件名、数据库文件名和表名作为参数,并将CSV文件中的数据转储到SQLite数据库的指定表中。代码使用了异常处理来捕获并打印错误信息,确保了连接的安全关闭。