66 lines
1.7 KiB
Python
66 lines
1.7 KiB
Python
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: str,SQLite 数据库路径
|
||
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} 个新组名。")
|