我的MySql数据库中有表:
我还有2个组合框:
我能够使用以下代码在数据库中使用表填充cmbHeader:
Dim conn As New MySqlConnection
Dim command As New MySqlCommand
Dim dt As New DataTable
conn.ConnectionString = "server=localhost;userid=root;password=NewPass;database=converter"
Try
conn.Open()
dt = conn.GetSchema("TABLES")
cmbHeader.DataSource = dt
cmbHeader.DisplayMember = "table_name"
cmbHeader.ValueMember = "table_name"
command.Dispose()
conn.Close()
Catch ex As Exception
End Try
现在对于cmbContent,我的代码中出现错误。我使用这段代码:
Private Sub cmbHeader_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbHeader.SelectedIndexChanged, cmbList.SelectedIndexChanged
Dim conn As New MySqlConnection
Dim command As New MySqlCommand
Dim dt As New DataTable
Dim reader As MySqlDataReader
conn.ConnectionString = "server=localhost;userid=root;password=NewPass;database=converter"
conn.Open()
Dim query As String
query = "SELECT * FROM '" & cmbHeader.SelectedItem & "'"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
cmbList.Items.Clear()
While reader.Read
Dim header = reader.GetString("Header")
Dim content = reader.GetString("Content")
Dim convert = reader.GetString("Convert")
cmbList.Items.Add(content)
End While
command.Dispose()
reader.Close()
conn.Close()
End Sub
这是我使用上面的代码得到的错误的图像。
我尝试将查询更改为" SELECT * FROM'" &安培; cmbHeader.SelectedItem.ToString& "'"但我得到了一个不同的错误。我如何根据我在第一个ComboBox上选择的内容填充我的第二个ComboBox?请帮助我卡住了。谢谢。 :)
答案 0 :(得分:0)
替换代码中的以下行
query = "SELECT * FROM '" & cmbHeader.SelectedItem & "'"
有了这一行,
query = "SELECT * FROM " & cmbHeader.SelectedItem.Value & ";"
希望这会奏效。 谢谢。
答案 1 :(得分:0)
使您的查询如下:
query = "SELECT * FROM " & cmbHeader.Text '<-- updation
OR
query = "SELECT * FROM " & cmbHeader.SelectedValue '<-- updation
但这不是一个好的做法,因为它导致sql injection所以我建议你使用参数化(在这种情况下可以避免伤害,因为它只允许组合框中的选定值。但总的来说这不是一个好的做法,这就是为什么我建议这样的)查询,如下所示
query = "SELECT * FROM ?"
Dim cmd As New OdbcCommand
With cmd
.CommandType = CommandType.Text
.CommandText = query
.Connection = con
.Parameters.Add(New OdbcParameter(@table,cmbHeader.SelectedItem ))
End With
答案 2 :(得分:-1)
对于其他有相同问题的人
我能够弄清楚我的代码有什么问题。组合框I的值返回&#34; Data.Row.DataRowView&#34;这就是我的查询失败的原因。我改变了这个:
cmbHeader.DataSource = dt
cmbHeader.DisplayMember = "table_name"
cmbHeader.ValueMember = "table_name"
进入这个:
cmbHeader.ValueMember = "table_name"
cmbHeader.DisplayMember = "table_name"
cmbHeader.DataSource = dt
然后在我的SelectedIndexChanged事件中,我使用了这个:
Dim value As String = ""
value = Convert.ToString(cmbHeader.Text)
conn.Open()
Dim query As String
query = "SELECT * FROM " & value
command = New MySqlCommand(query, conn)
'With command
' .Parameters.AddWithValue("header", value)
'End With
reader = command.ExecuteReader
cmbList.Items.Clear()
While reader.Read
Dim content = reader.GetString("Content")
cmbList.Items.Add(content)
End While
command.Dispose()
reader.Close()
conn.Close()
希望这会有所帮助。感谢大家的帮助。 :)