编写用户登录时使用VB和SQL Server登录的代码,可以按照以下步骤进行:
以下是一个示例代码:
Imports System.Data.SqlClient
Public Class LoginForm
Dim conn As SqlConnection
Private Sub LoginForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' 连接数据库
conn = New SqlConnection("Data Source=服务器地址;Initial Catalog=数据库名称;User ID=用户名;Password=密码")
conn.Open()
End Sub
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim username As String = txtUsername.Text
Dim password As String = txtPassword.Text
' 执行查询
Dim query As String = "SELECT * FROM 用户表 WHERE 用户名 = @username"
Dim cmd As New SqlCommand(query, conn)
cmd.Parameters.AddWithValue("@username", username)
Dim reader As SqlDataReader = cmd.ExecuteReader()
' 验证登录
If reader.Read() Then
Dim dbPassword As String = reader("密码").ToString()
If password = dbPassword Then
MessageBox.Show("登录成功")
Else
MessageBox.Show("密码错误")
End If
Else
MessageBox.Show("用户名不存在")
End If
reader.Close()
End Sub
Private Sub LoginForm_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
' 关闭数据库连接
conn.Close()
End Sub
End Class
请注意,上述代码仅为示例,需要根据实际情况进行修改和适配。另外,为了安全起见,建议使用哈希算法对密码进行加密存储,并在验证时比对哈希值。
领取专属 10元无门槛券
手把手带您无忧上云