关于AI写脚本的一点感想

Posted by wukaiqiang; tagged with none

花了1天时间, 通过AI的辅助,写了一个批量修改数据库的图形化小工具, 通过本地测试,功能基本都实现了,满足预期。但是也遇到了一些没法跳过的问题,就像自动驾驶一样,后面还是得有人负责,所以这个脚本最终还是不能上线,因为我没法为数据库修改工具产生的bug买单。可能得意外会是灾难性的。写高质量的,没有或少有bug的代码很难。功能越多,可能得问题就越多。

import tkinter as tk
from tkinter import messagebox
import pymysql
from datetime import datetime

读取数据库信息

def read_db_info(file_path):

db_info = []
with open(file_path, 'r') as file:
    for line in file:
        db_info.append(line.strip().split(','))  # 假设文本文件中每行格式为:IP,port,username,password,database
return db_info

执行 SQL 语句并记录日志

def execute_sql(sql, db_info, log_file, result_text, log_text, show_result):

current_datetime = datetime.now().strftime("%Y-%m-%d-%H%M")  # 获取当前日期时间并格式化为字符串
log_file_with_datetime = f"{log_file}_{current_datetime}.txt"  # 构建带有日期时间后缀的日志文件名
for info, checkbox_var in zip(db_info, checkbox_vars):
    ip = info[0]
    port = int(info[1])  # 转换为整数
    username = info[2]
    password = info[3]
    database = info[4]

    if checkbox_var.get():  # 如果勾选了该数据库
        try:
            # 连接数据库
            connection = pymysql.connect(host=ip, port=port, user=username, password=password, database=database)
            cursor = connection.cursor()

            # 执行 SQL
            cursor.execute(sql)
            result = cursor.fetchall()  # 获取执行结果
            connection.commit()

            # 记录日志
            log_msg = f"执行 SQL 成功:IP={ip}, Port={port}, Database={database}, SQL={sql}"
            with open(log_file_with_datetime, 'a') as logfile:
                logfile.write(log_msg + '\n')

            # 在结果文本框中显示执行结果(如果允许显示)
            if show_result:
                result_text.insert(tk.END, str(result) + '\n')

            # 在日志文本框中显示日志信息
            log_text.insert(tk.END, log_msg + '\n')

            # 关闭连接
            cursor.close()
            connection.close()

        except Exception as e:
            # 打印报错信息并记录日志
            error_msg = f"执行 SQL 出错:IP={ip}, Port={port}, Database={database}, 错误信息={str(e)}"
            with open(log_file_with_datetime, 'a') as logfile:
                logfile.write(error_msg + '\n')

            # 在日志文本框中显示错误日志信息
            log_text.insert(tk.END, error_msg + '\n')

执行按钮点击事件

def execute_button_clicked():

sql = sql_entry.get("1.0", tk.END)  # 获取 SQL 输入框中的内容
execute_sql(sql, db_info, "execution_log", result_text, log_text, show_result_var.get())

切换是否显示执行结果

def toggle_result_display():

if show_result_var.get():
    result_text.pack()
else:
    result_text.pack_forget()

创建主窗口

root = tk.Tk()
root.title("mysql批量管理工具")

读取数据库信息

db_info = read_db_info("db_info.txt")

创建连接信息框架

connection_frame = tk.LabelFrame(root, text="数据库连接信息", padx=10, pady=10)
connection_frame.pack(side=tk.LEFT, padx=10, pady=10, fill=tk.Y)

显示数据库信息和勾选框

checkbox_vars = [] # 用于存储勾选框的变量
for info in db_info:

checkbox_var = tk.BooleanVar(value=True)  # 默认勾选
checkbox_vars.append(checkbox_var)
checkbox = tk.Checkbutton(connection_frame, text=f"{info[0]}:{info[1]}({info[4]})", variable=checkbox_var)
checkbox.pack(anchor=tk.W)

创建 SQL 输入框和标签

sql_label = tk.Label(root, text="请输入 SQL:")
sql_label.pack(pady=(10, 0))
sql_entry = tk.Text(root, width=150, height=10)
sql_entry.pack()

创建是否显示执行结果的 Checkbutton

show_result_var = tk.BooleanVar(value=True) # 默认显示执行结果
show_result_button = tk.Checkbutton(root, text="显示执行结果", variable=show_result_var, command=toggle_result_display)
show_result_button.pack(side=tk.TOP, anchor=tk.NE) # 放置在右上角

创建执行按钮

execute_button = tk.Button(root, text="执行 SQL", command=execute_button_clicked, width=20, height=2)
execute_button.pack(pady=10)

创建结果文本框和滚动条

result_frame = tk.LabelFrame(root, text="执行结果", padx=10, pady=10)
result_frame.pack(side=tk.RIGHT, padx=10, pady=10, fill=tk.BOTH, expand=True)
result_text = tk.Text(result_frame, width=50, height=10)
result_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
result_scroll = tk.Scrollbar(result_frame, command=result_text.yview)
result_scroll.pack(side=tk.RIGHT, fill=tk.Y)
result_text.config(yscrollcommand=result_scroll.set)

创建日志文本框和滚动条

log_frame = tk.LabelFrame(root, text="日志信息", padx=10, pady=10)
log_frame.pack(side=tk.RIGHT, padx=10, pady=10, fill=tk.BOTH, expand=True)
log_text = tk.Text(log_frame, width=50, height=10)
log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
log_scroll = tk.Scrollbar(log_frame, command=log_text.yview)
log_scroll.pack(side=tk.RIGHT, fill=tk.Y)
log_text.config(yscrollcommand=log_scroll.set)

运行主循环

root.mainloop()