您好我确定这是一个非常简单的问题需要解决,但我对此非常陌生,只是在线阅读教程,但我无法根据自己的需要调整代码。基本上,当我尝试在我的数据库中使用nvarchar而不是int作为我的用户名和密码列时,我不断收到以下错误:
类型' System.Data.SqlClient.SqlException'未处理的异常 发生在System.Data.dll
中
这是我的代码:
Public Class Login
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim con As New SqlClient.SqlConnection(MyConnection.MyConnectionString)
con.Open()
Dim dr As SqlClient.SqlDataReader
Dim cmd As New SqlClient.SqlCommand("select * from [customer_login] where username=" + tbUsename.Text + " and password=" + tbPassword.Text + "", con)
dr = cmd.ExecuteReader
If dr.Read Then
MsgBox("you are logged on as" + tbUsename.Text + "put logged in home page here")
End If
End Sub
End Class
编辑:完整的错误消息是:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid column name 'a123'.
Invalid column name 'a123'.
答案 0 :(得分:2)
您拥有的代码会生成以下SQL:
select * from [customer_login] where username=user and password=pass
user
和pass
是在文本框中输入的值。那是无效的SQL,值需要引用字符串。或者甚至更好,它们应该是named parameters以防止一类名为SQL injection的攻击,或者仅仅是为了防止用户名称中包含撇号并且在运行时构建的SQL语句具有因此错误。
将来,您应该使用Try .. Catch块来捕获异常并在调试器中查看异常的内容。在这种情况下,它会在SQL语句中快速显示错误。
答案 1 :(得分:0)
您的查询中缺少单引号
Public Class Login
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
Dim con As New SqlClient.SqlConnection(MyConnection.MyConnectionString)
con.Open()
Dim dr As SqlClient.SqlDataReader
Dim cmd As New SqlClient.SqlCommand("select * from [customer_login] where username='" + tbUsename.Text + "' and password='" + tbPassword.Text + "'", con)
dr = cmd.ExecuteReader
If dr.Read Then
MsgBox("you are logged on as" + tbUsename.Text)
'put logged in home page here.show()
End If
End Sub
End Class