我有一个表名称stocks,其中包含以下列:
ItemID, Item, Serial, Quantity, Category, Class, Unit, Beg_Date
这是我在 vb.net 上编写的代码:
Private Sub Savebtn_Click(sender As Object, e As EventArgs) Handles Savebtn.Click
Try
If txtItemID.Text = "" Or txtItemName.Text = "" Or txtQuantity.Text = "" Or cBoxCategory.Text = "" Or cBoxClass.Text = "" Or cBoxUnit.Text = "" Or dtpAdd.Value =""Then
MsgBox("All fields required!")
Else
ConStr.Open()
Dim Add_Query As String
Add_Query = "INSERT INTO Stocks (ItemID,Item,Serial,Quantity,Category,Class,Unit,Beg_Date) VALUES ('" & txtItemID.Text & "','" & txtItemName.Text & "','" & txtSerial.Text & "','" & txtQuantity.Text & "','" & cBoxCategory.Text & "','" & cBoxClass.Text & "','" & cBoxUnit.Text & "','" & dtpAdd.Value & "')"
Cmd = New MySqlCommand(Add_Query, ConStr)
Rdr = Cmd.ExecuteReader
MsgBox("Successfully Added!")
Me.Hide()
ConStr.Close()
End If
Catch ex As MySqlException
MsgBox("Connection Failed!")
Finally
ConStr.Dispose()
End Try
End Sub
每次我在用户输入值时保存数据时,它总是给我一个
Mysqlexception error "Connection Failed!"..
知道如何解决这个问题吗?
最佳答案
确保您已关闭之前的所有连接。添加行
If(ConStr != ConnectionState.Open)
再次打开连接之前
这将在您尝试再次打开连接之前检查连接是否已打开。
对于 Catch,使用
MsgBox("Connection Failed!" & Ex.Message)
显示实际抛出的异常。
此外,除非您需要返回记录,否则使用 Cmd.ExecuteNonQuery() 是运行操作查询的首选方法。
关于mysql - 在mysql和vb.net上插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32063052/