Files
fastcopy/ntfs_utils/db_group.py
2025-05-15 16:33:30 +08:00

66 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import sqlite3
def InsertGroupToDB(group_name_list, db_path='../src/db_ntfs_info.db', table_name='db_group'):
"""
向用户组表中插入多个组名。
参数:
group_name_list: list of str要插入的组名列表
db_path: strSQLite 数据库路径
table_name: str用户组表名
返回:
int: 成功插入的记录数
"""
if not isinstance(group_name_list, list):
raise TypeError("group_name_list 必须是一个列表")
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,
GroupName TEXT UNIQUE NOT NULL
);
"""
cursor.execute(create_table_sql)
# 构建插入数据格式
insert_sql = f"""
INSERT OR IGNORE INTO {table_name} (GroupName)
VALUES (?)
"""
data_to_insert = [(name,) for name in group_name_list]
# 批量插入
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__":
groups = ["Copier", "Admin", "Guest", "Developer"]
count = InsertGroupToDB(groups)
print(f"共插入 {count} 个新组名。")