69 lines
2.4 KiB
Python
69 lines
2.4 KiB
Python
import sqlite3
|
|
from db_utils import get_db_connection, close_db_connection
|
|
|
|
|
|
def remove_department_from_query_history():
|
|
"""
|
|
从query_history表中删除department字段
|
|
SQLite不支持直接删除列,采用以下步骤:
|
|
1. 创建一个不包含department字段的新表
|
|
2. 将原始表中的数据(除department外)复制到新表
|
|
3. 删除原始表
|
|
4. 重命名新表为原始表名
|
|
5. 重新创建索引和外键约束
|
|
"""
|
|
conn = None
|
|
try:
|
|
# 获取数据库连接
|
|
conn = get_db_connection()
|
|
cursor = conn.cursor()
|
|
|
|
print("开始从query_history表中删除department字段...")
|
|
|
|
# 1. 创建临时表,不包含department字段
|
|
print("1. 创建临时表query_history_new...")
|
|
cursor.execute('''
|
|
CREATE TABLE IF NOT EXISTS query_history_new (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
query_date TEXT NOT NULL,
|
|
plate_number TEXT,
|
|
phone TEXT,
|
|
results_count INTEGER NOT NULL,
|
|
query_ip TEXT NOT NULL,
|
|
user_id INTEGER,
|
|
FOREIGN KEY (user_id) REFERENCES users (id)
|
|
)
|
|
''')
|
|
|
|
# 2. 复制数据到新表,排除department字段
|
|
print("2. 复制数据到新表,排除department字段...")
|
|
cursor.execute('''
|
|
INSERT INTO query_history_new (id, query_date, plate_number, phone, results_count, query_ip, user_id)
|
|
SELECT id, query_date, plate_number, phone, results_count, query_ip, user_id
|
|
FROM query_history
|
|
''')
|
|
|
|
# 3. 删除原表
|
|
print("3. 删除原始表query_history...")
|
|
cursor.execute('DROP TABLE IF EXISTS query_history')
|
|
|
|
# 4. 重命名新表为原表名
|
|
print("4. 重命名新表为query_history...")
|
|
cursor.execute('ALTER TABLE query_history_new RENAME TO query_history')
|
|
|
|
# 5. 提交事务
|
|
conn.commit()
|
|
print("操作完成:department字段已成功从query_history表中删除!")
|
|
|
|
except sqlite3.Error as e:
|
|
print(f"数据库操作出错:{e}")
|
|
if conn:
|
|
conn.rollback()
|
|
raise
|
|
finally:
|
|
if conn:
|
|
close_db_connection(conn)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
remove_department_from_query_history() |