72 lines
3.0 KiB
Python
72 lines
3.0 KiB
Python
import sqlite3
|
|
|
|
# 连接到数据库并确保users表结构正确
|
|
def update_users_table():
|
|
try:
|
|
# 连接数据库
|
|
conn = sqlite3.connect('car_info.db')
|
|
cursor = conn.cursor()
|
|
|
|
# 检查users表的当前结构
|
|
cursor.execute("PRAGMA table_info(users)")
|
|
columns = [column[1] for column in cursor.fetchall()]
|
|
print(f"当前users表的字段: {columns}")
|
|
|
|
# 使用不同的方法来添加字段,避免NOT NULL约束可能导致的问题
|
|
if 'name' not in columns:
|
|
# 先添加可为空的字段
|
|
cursor.execute("ALTER TABLE users ADD COLUMN name TEXT")
|
|
# 然后设置默认值并更新现有数据
|
|
cursor.execute("UPDATE users SET name = '未知用户' WHERE name IS NULL")
|
|
print("已添加name字段并设置默认值")
|
|
|
|
if 'phone' not in columns:
|
|
# 先添加可为空的字段
|
|
cursor.execute("ALTER TABLE users ADD COLUMN phone TEXT")
|
|
# 然后设置默认值并更新现有数据
|
|
cursor.execute("UPDATE users SET phone = '00000000000' WHERE phone IS NULL")
|
|
print("已添加phone字段并设置默认值")
|
|
|
|
if 'department' not in columns:
|
|
# 先添加可为空的字段
|
|
cursor.execute("ALTER TABLE users ADD COLUMN department TEXT")
|
|
# 然后设置默认值并更新现有数据
|
|
cursor.execute("UPDATE users SET department = '未知部门' WHERE department IS NULL")
|
|
print("已添加department字段并设置默认值")
|
|
|
|
# 无条件更新admin用户的信息,确保所有字段都有值
|
|
cursor.execute(
|
|
"UPDATE users SET name = ?, phone = ?, department = ? WHERE username = ?",
|
|
('管理员', '13800138000', 'IT部', 'admin')
|
|
)
|
|
print("已更新admin用户信息")
|
|
|
|
# 提交更改
|
|
conn.commit()
|
|
|
|
# 再次验证表结构
|
|
cursor.execute("PRAGMA table_info(users)")
|
|
updated_columns = cursor.fetchall()
|
|
print("\n更新后的users表字段:")
|
|
for col in updated_columns:
|
|
print(f"字段名: {col[1]}, 类型: {col[2]}")
|
|
|
|
# 检查admin用户的信息是否正确更新
|
|
cursor.execute("SELECT id, username, name, phone, department FROM users WHERE username = ?", ('admin',))
|
|
admin_user = cursor.fetchone()
|
|
if admin_user:
|
|
print("\n更新后的admin用户信息:")
|
|
print(f"ID: {admin_user[0]}, 用户名: {admin_user[1]}, 姓名: {admin_user[2]}, 电话: {admin_user[3]}, 部门: {admin_user[4]}")
|
|
|
|
# 关闭连接
|
|
conn.close()
|
|
print("\n数据库更新完成")
|
|
|
|
except Exception as e:
|
|
print(f"更新数据库时出错: {str(e)}")
|
|
# 确保在异常情况下也关闭连接
|
|
if 'conn' in locals():
|
|
conn.close()
|
|
|
|
if __name__ == "__main__":
|
|
update_users_table() |