我的Windows窗体中有两个列表框,其中第一个包含一堆ID,当选择ID时,MySQL数据库中的所有属性都使用第二个列表框显示。
我的代码:
Private Sub lstUsersKey_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstUsersKey.SelectedIndexChanged
If (lstUsersKey.SelectedIndex.ToString IsNot Nothing) Then
Dim UserID As Integer = CInt(lstUsersKey.SelectedItem.ToString)
lstUsersValue.Items.Clear()
lstUsersValue.Items.Add("User ID: " & UserID)
lstUsersValue.Items.Add("Forename: " & frmLogin.User.GetForename)
lstUsersValue.Items.Add("Surname: " & frmLogin.User.GetSurname)
lstUsersValue.Items.Add("Admin: " & frmLogin.User.IsAdmin)
lstUsersValue.Items.Add("Username: " & frmLogin.User.GetUsername)
lstUsersValue.Items.Add("Password: -") '& frmLogin.User.GetPassword
lstUsersValue.Items.Add("Phone Number: " & frmLogin.User.GetPhoneNumber)
lstUsersValue.Items.Add("Address: " & frmLogin.User.GetAddress())
lstUsersValue.Items.Add("Postcode: " & frmLogin.User.GetPostcode())
lstUsersValue.Items.Add("Email Address: " & frmLogin.User.GetUserEmailAddress)
End If
End Sub
我的User类中的函数看起来像这样但具有不同的参数:
Function GetPostcode()
Return frmLogin.MySQL.SelectQuery("Postcode", "tbluser", "Username", "@username", Me.Username)
End Function
我的MySQL类包含此功能:
Function SelectQuery(ByVal ColumnName As String, ByVal tblName As String, ByVal ConditionColumn As String, ByVal ConditionCheckOperator As String, ByVal ConditionCheckValue As String)
Dim Query As String = "SELECT " & ColumnName & " " & "FROM " & tblName & " " & "WHERE " & ConditionColumn & "=" & ConditionCheckOperator
Dim Connection As New MySqlConnection(frmLogin.MySQL.ConnectionDetails)
Dim Command = New MySqlCommand(Query, Connection)
Connection.Open()
Dim Result As Object
Command.Parameters.AddWithValue(ConditionCheckOperator, ConditionCheckValue)
Result = Command.ExecuteScalar
Command.Dispose()
Connection.Close()
If Result IsNot Nothing Then
Return Result.ToString
Else
Return ""
End If
End Function
问题是没有从我的数据库加载数据,我不知道如何修复它以及是否有更简单的方法来运行大量查询而无需每次我想运行时都建立新的连接查询。
答案 0 :(得分:0)
所以我通过改变SelectQuery Function的工作方式解决了这个问题。我找到了一种在stackoverflow上运行查询的有效方法,所以我复制了代码并对其进行了调整。
Function SelectQuery(ByVal ColumnName As String, ByVal tblName As String, ByVal ConditionColumn As String, ByVal Operator1 As String, ByVal Value1 As Object)
Dim Query As String = "SELECT " & ColumnName & " " & "FROM " & tblName & " " & "WHERE " & ConditionColumn & "=" & Operator1
Dim Result As String = ""
Using Conn As New MySqlConnection(ConnectionDetails)
Using Comm As New MySqlCommand()
With Comm
.Connection = Conn
.CommandText = Query
.CommandType = CommandType.Text
.Parameters.AddWithValue(Operator1, Value1)
End With
Try
Conn.Open()
Dim Reader As MySqlDataReader = Comm.ExecuteReader
While Reader.Read() OrElse (Reader.NextResult And Reader.Read)
Result += Reader.GetString(0)
End While
Catch ex As Exception
Return "Error"
MsgBox("select error: " & ex.ToString)
End Try
End Using
End Using
Return Result
End Function