Sql server VB.NET SQL Server选择计数(*)-ExecuteOnQuery:尚未初始化连接属性
我的登录页面代码为VB.NET,如下所示:Sql server VB.NET SQL Server选择计数(*)-ExecuteOnQuery:尚未初始化连接属性,sql-server,vb.net,Sql Server,Vb.net,我的登录页面代码为VB.NET,如下所示: Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click Try If UsernameTextBox.Text = "" Then MsgBox("Insert your username.") UsernameTextBox.Focus()
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Try
If UsernameTextBox.Text = "" Then
MsgBox("Insert your username.")
UsernameTextBox.Focus()
Return
ElseIf PasswordTextBox.Text = "" Then
MsgBox("Insert your Passwprd.")
PasswordTextBox.Focus()
Return
Else
Dim count As Integer
Using con As New OleDbConnection("Provider=SQLOLEDB;Data Source=JUNIOR-PC\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=ShopHereNow")
con.Open()
Dim command = New OleDbCommand("Select count(*) from Employees where FirstName = '" & UsernameTextBox.Text & "' and [Password] = '" & PasswordTextBox.Text & "'")
count = command.ExecuteNonQuery()
con.Close()
If count > 0 Then
MsgBox("Welcome " & UsernameLabel.Text & "!")
Me.Hide()
Home.Show()
Else
MessageBox.Show("Invalid combination. Try again...")
Cancel.PerformClick()
Return
End If
End Using
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "ERROR5", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
在执行这段代码时,我得到一个错误:ExecuteNonQuery:Connection属性尚未初始化
请帮忙,我在哪里可以编错代码?您的代码有一些错误 使用参数化查询: 为了安全起见,这是为了避免SQL注入攻击 上述错误是因为您尚未在命令中指定连接,请将FirstName=@FirstName and Password=@Password=@Password的员工的Dim command=New OLEDBCOMANDSELECT count*更改为FirstName=@FirstName and Password=@Password的员工的Dim command=New OLEDBCOMAND SELECT count*,共**** MsgBox是不推荐使用的方法,请改用MessegeBox.Show 不要使用类异常。而是指定特定的异常类型。在这里,您可能需要SQLException
在调用查询之前,您需要将命令链接到连接,例如command.connection=con。VS中是否有一条警告,说明MsgBox是一种不推荐使用的方法?我不记得这是一个不推荐的方法。我只知道MessageBox.Show更受欢迎,因为您可以在C中轻松使用它。只有在导入Microsoft.VisualBasic命名空间时,MsgBox才在C中可用。VB项目默认导入这个名称空间。非常感谢我做了你提到的更改,错误得到了解决。但是,如何在上面的代码中获取变量“count”的值?@KeithJnrP.Mthembu:不客气。但我不明白。现在有什么问题?程序应该可以正常运行。@Handoko.Chen:谢谢通知。事实上,并没有关于反对的警告。是我在什么地方读到的。事实上,我不记得来源,但谢谢你的启发
Dim command = New OleDbCommand("Select count(*) from Employees where FirstName =@FirstName and Password = @Password")
command.Parameters.AddWithValue("@FirstName", UsernameTextBox.Text)
command.Parameters.AddWithValue("@Password", PasswordTextBox.Text)