如何使用python语言结合sqlserver制作登录窗口,请写出详细操作过程和相应的完整代码
时间: 2024-04-29 11:25:32 浏览: 165
操作过程:
1. 安装pymssql库
在命令行中输入以下命令:
```
pip install pymssql
```
2. 创建GUI登录窗口
使用Python的Tkinter模块创建GUI窗口,包括用户名输入框、密码输入框和登录按钮。
3. 连接SQL Server
使用pymssql库连接SQL Server数据库。
4. 验证用户名和密码
在登录按钮点击事件中,使用输入的用户名和密码查询数据库,验证是否正确。
5. 关闭数据库连接
在验证完毕后,关闭数据库连接。
完整代码:
```
import tkinter as tk
import pymssql
def login():
# 连接数据库
conn = pymssql.connect(server='localhost', user='sa', password='123456', database='mydb')
cursor = conn.cursor()
# 查询用户是否存在
username = entry_username.get()
password = entry_password.get()
sql = "SELECT COUNT(*) FROM users WHERE username=%s AND password=%s"
cursor.execute(sql, (username, password))
result = cursor.fetchone()
# 关闭数据库连接
cursor.close()
conn.close()
# 验证用户名和密码
if result[0] == 1:
label_result.config(text="登录成功")
else:
label_result.config(text="用户名或密码错误")
# 创建GUI窗口
window = tk.Tk()
label_username = tk.Label(window, text="用户名:")
label_username.pack()
entry_username = tk.Entry(window)
entry_username.pack()
label_password = tk.Label(window, text="密码:")
label_password.pack()
entry_password = tk.Entry(window, show="*")
entry_password.pack()
button_login = tk.Button(window, text="登录", command=login)
button_login.pack()
label_result = tk.Label(window, text="")
label_result.pack()
window.mainloop()
```
说明:
1. 在连接数据库时,需要提供SQL Server的地址、用户名、密码和数据库名。
2. 在查询时使用参数化查询,防止SQL注入攻击。
3. 查询结果为一个元组,取第一个元素表示查询到的记录数。
4. 在关闭数据库连接时,需要先关闭游标再关闭连接。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)