1
工作
我ComboBox
控制顯示PUBLISHERNAME和authorlastname和存儲的publisherId和AUTHORID。組合框ValueMember不使用MySQL
當我運行我的代碼,但它確實顯示PUBLISHERNAME和authorlastname與ValueMember
的的publisherId和的AUTHORID然而,當插入查詢運行它的字面試圖插入的話_publisherid_
和_authorid_
。
組合框代碼:
Private Sub addbook_Load(sender As Object, e As EventArgs) Handles MyBase.Load
mysqlconn = New MySqlConnection
mysqlconn.ConnectionString = "server=localhost;userid=root;database=librarydatabase;Convert Zero Datetime=True"
Dim table As New DataTable
Dim da As New MySqlDataAdapter("select * from publishertable", mysqlconn)
da.Fill(table)
ComboBox1.DataSource = New BindingSource(table, Nothing)
ComboBox1.DisplayMember = "publishername"
ComboBox1.ValueMember = "PublisherId"
Dim pa As New MySqlDataAdapter("select * from authortable", mysqlconn)
pa.Fill(table)
ComboBox2.DataSource = New BindingSource(table, Nothing)
ComboBox2.DisplayMember = "authorlastname"
ComboBox2.ValueMember = "authorid"
End Sub
插入代碼:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button1.Click
conn = New MySqlConnection
conn.ConnectionString =
"server=localhost;userid=root;database=librarydatabase"
Dim reader As MySqlDataReader
Try
conn.Open()
query = "SET foreign_key_checks = 0;insert into booktable(ISBNno,bookname,dateofpublication,genre,duodecimal,copies,copiesinstock,authorid,publisherid) Values('" & ISBNno.Text & "','" & Title.Text & "','" & dateofpublication.Text & "','" & genre.Text & "','" & duodecimal.Text & "','" & copies.Text & "','" & copies.Text & "','" & ComboBox2.ValueMember & "', '" & ComboBox1.ValueMember & "');SET foreign_key_checks = 1"
command = New MySqlCommand(query, conn)
reader = command.ExecuteReader
MessageBox.Show(query)
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
你應該使用'SelectedValue'而不是'ValueMember' – bansi
如果你想在數據庫中保存發佈者名稱,傳遞ComboBox1.SelectedText。 – PRABA
您的代碼可能容易受到SQL注入,轉換錯誤和數據截斷的影響[您應該**總是**使用參數化查詢。](https://blog.codinghorror.com/give-me-parameterized-sql-或給我死/) – GarethD