利用Python(一种编程语言)的PyMySQL模块实现了连接MySQL内容,实现了注册用户,并把用户密码传入MySQL数据库

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import pymysql
import customtkinter

def connect_db():
"""连接数据库函数

Args:
None

Returns:
pymysql.connections.Connection: 数据库连接对象,若连接失败则返回None
"""

try:
# 替换为你的数据库连接信息
conn = pymysql.connect(
host = 'mysql.sqlpub.com', # 连接主机, 默认127.0.0.1
user = 'yuxuan1012', # 用户名
passwd = 'Ki1jpS4leURR4TFu',# 密码
port = 3306, # 端口,默认为3306
db = 'yuxuan1012', # 数据库名称
charset = 'utf8' # 字符编码
)
return conn
except pymysql.err.OperationalError as e:
print(f"数据库连接失败:{e}")
customtkinter.messagebox.showerror("错误", "连接数据库失败,请检查网络和数据库配置。")
return None # 返回None表示连接失败

def register():
"""用户注册函数

Args:
None
"""

# 获取用户输入
username = entry_username.get()
password = entry_password.get()
confirm_password = entry_confirm_password.get()

# 密码校验
if password != confirm_password:
customtkinter.messagebox.showwarning("警告", "两次输入的密码不一致!")
return

# 连接数据库
conn = connect_db()

if conn:
try:
with conn.cursor() as cursor:
# 检查表是否存在,如果不存在则创建
cursor.execute("SHOW TABLES LIKE 'users'")
exists = cursor.fetchone()
if not exists:
cursor.execute("CREATE TABLE users (username VARCHAR(50), password VARCHAR(50))")

# 执行插入用户信息的SQL语句
sql = "INSERT INTO users (username, password) VALUES (%s, %s)"
cursor.execute(sql, (username, password))
conn.commit()
print("注册成功!")
except pymysql.err.Error as e:
# 处理数据库操作异常
print(f"数据库操作错误:{e}")
customtkinter.messagebox.showerror("错误", "注册失败,请检查数据库配置或联系管理员。")
finally:
# 确保连接关闭
conn.close()
else:
# 连接失败,显示错误信息
customtkinter.messagebox.showerror("错误", "注册失败,请检查网络连接或管理员。")

# 创建界面部分(省略,与之前代码相同)

# 创建界面
customtkinter.set_appearance_mode("Dark") # Modes: "System" (standard), "Dark", "Light"
customtkinter.set_default_color_theme("green") # Themes: "blue" (standard), "green", "dark-blue"

root = customtkinter.CTk()
root.geometry("400x300")

frame = customtkinter.CTkFrame(master=root)
frame.pack(pady=20, padx=60, fill="both", expand=True)

label = customtkinter.CTkLabel(master=frame, text="注册", font=("Roboto", 24))
label.pack(pady=12, padx=10)

entry_username = customtkinter.CTkEntry(master=frame, placeholder_text="注册用户名")
entry_username.pack(pady=12, padx=10)
entry_password = customtkinter.CTkEntry(master=frame, placeholder_text="注册密码", show="*")
entry_password.pack(pady=12, padx=10)
entry_confirm_password = customtkinter.CTkEntry(master=frame, placeholder_text="确认密码", show="*")
entry_confirm_password.pack(pady=12, padx=10)

button = customtkinter.CTkButton(master=frame, text="注册", command=register)
button.pack(pady=12, padx=10)

root.mainloop()

后续准备:实现密码加密,防止被透底,加入登录代码………
明天去找一个朋友下棋,还说在什么棋牌室,等着今晚我要看看高德地图,那儿到底在哪里啊
刚才下雨了下的不小,希望现在能停雨。