69 lines
1.9 KiB
Python
69 lines
1.9 KiB
Python
import sqlite3
|
||
|
||
|
||
def InsertExtensionsToDB(extensions, db_path='../src/db_ntfs_info.db', table_name='db_extend_name'):
|
||
"""
|
||
将扩展名列表插入到数据库中,自动忽略重复项。
|
||
|
||
参数:
|
||
extensions: list of str,要插入的扩展名列表(如 ["txt", "jpg"])
|
||
db_path: str,SQLite 数据库路径
|
||
table_name: str,扩展名表名
|
||
|
||
返回:
|
||
int: 成功插入的新记录数量
|
||
"""
|
||
if not isinstance(extensions, list):
|
||
raise TypeError("extensions 必须是一个列表")
|
||
|
||
conn = sqlite3.connect(db_path)
|
||
cursor = conn.cursor()
|
||
|
||
try:
|
||
# 创建表(如果不存在)
|
||
create_table_sql = f"""
|
||
CREATE TABLE IF NOT EXISTS {table_name} (
|
||
ID INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
ExtendName TEXT UNIQUE NOT NULL
|
||
);
|
||
"""
|
||
cursor.execute(create_table_sql)
|
||
|
||
# 插入语句(忽略重复)
|
||
insert_sql = f"""
|
||
INSERT OR IGNORE INTO {table_name} (ExtendName)
|
||
VALUES (?)
|
||
"""
|
||
|
||
# 构造插入数据格式
|
||
data_to_insert = [(ext.lower(),) for ext in extensions if ext.strip()]
|
||
|
||
# 批量插入
|
||
cursor.executemany(insert_sql, data_to_insert)
|
||
conn.commit()
|
||
|
||
inserted_count = cursor.rowcount
|
||
if inserted_count > 0:
|
||
print(f"✅ 成功插入 {inserted_count} 个扩展名")
|
||
else:
|
||
print("⚠️ 没有新的扩展名被插入(可能已存在)")
|
||
|
||
return inserted_count
|
||
|
||
except Exception as e:
|
||
print(f"❌ 插入失败: {e}")
|
||
conn.rollback()
|
||
return 0
|
||
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
# 示例调用
|
||
if __name__ == "__main__":
|
||
# 常见的文件扩展名列表(可选)
|
||
common_extensions = ["txt", "log", "csv", "xls", "xlsx", "doc", "docx"]
|
||
|
||
count = InsertExtensionsToDB(common_extensions)
|
||
print(f"共插入 {count} 个新扩展名。")
|