我正在尝试在 VB.NET 中创建登录表单。 我在运行表单时遇到一些困难



我收到错误"无效的转换异常未处理"。我使用的是SQL Server 2008和Visual Studio 2008。我从字符串"杰克"到类型布尔值的转换无效。

请参阅下面的表单代码:

Imports System.Boolean
Imports System.Data.SqlClient
Public Class Form1
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim username As String
        Dim pswd As String
        Dim conn As SqlConnection
        Dim cmd As SqlCommand
        Dim reader As SqlDataReader
        username = txt_username.Text
        pswd = txt_password.Text
        txt_username.Text = Focus()
        txt_password.Visible = "False"
        Try
            conn = New SqlConnection("data source=TAMIZHANSQLEXPRESS;persistsecurity info=False;initial catalog=log;User ID=sa;Password=123");
            cmd = New SqlCommand("Select usename,passw from Userlog where usename='" + username + "' & passw='" + pswd + "'")
            conn.Open()
            reader = cmd.ExecuteReader()
            If (String.Compare(pswd and '"+passw+"')) Then
                MsgBox("Success")
            End If
            If (reader.Read()) Then
                MsgBox("Login success")
            End If
            conn.Close()
        Catch ex As Exception
            MsgBox("Error"+ex.Message());
        End Try
    End Sub
End Class

字符串。比较返回一个整数而不是布尔值,应该以这种方式调用

If (String.Compare(pswd,passw) = 0) Then 
    MsgBox("Success") 
End If 

请参阅MSDN上的参考资料

但是,您的代码现在存在许多问题:

  • 您正在使用字符串串联来构建 sql 文本(SqlInjection,引用问题)。
  • 不使用 Using 语句(在例外)。
  • 比较逻辑似乎绝对不需要。

最新更新