init database expect db_node
This commit is contained in:
66
ntfs_utils/db_user.py
Normal file
66
ntfs_utils/db_user.py
Normal file
@@ -0,0 +1,66 @@
|
||||
import sqlite3
|
||||
|
||||
|
||||
def InsertUserToDB(username_list, db_path='../src/db_ntfs_info.db', table_name='db_user'):
|
||||
"""
|
||||
向用户表中插入多个用户名。
|
||||
|
||||
参数:
|
||||
username_list: list of str,要插入的用户名列表
|
||||
db_path: str,SQLite 数据库路径
|
||||
table_name: str,用户表名
|
||||
|
||||
返回:
|
||||
int: 成功插入的新用户数量
|
||||
"""
|
||||
if not isinstance(username_list, list):
|
||||
raise TypeError("username_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,
|
||||
UserName TEXT UNIQUE NOT NULL
|
||||
);
|
||||
"""
|
||||
cursor.execute(create_table_sql)
|
||||
|
||||
# 插入语句(忽略重复)
|
||||
insert_sql = f"""
|
||||
INSERT OR IGNORE INTO {table_name} (UserName)
|
||||
VALUES (?)
|
||||
"""
|
||||
|
||||
# 构建数据格式
|
||||
data_to_insert = [(name,) for name in username_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__":
|
||||
users = ["Alice", "Bob", "Charlie", "David"]
|
||||
count = InsertUserToDB(users)
|
||||
print(f"共插入 {count} 个新用户。")
|
Reference in New Issue
Block a user