VB插入MySql

时间:2015-05-18 12:31:15

标签: mysql vb.net

作为Vb noob我正在研究这个学校项目。我需要将我的值插入我的mysql数据库,但由于一个原因,它没有插入尝试的一切,但我找不到为什么它不插入。 Thx提前

 Dim sqlCommand As New MySqlCommand
    Dim SQLConnection As MySqlConnection = New MySqlConnection
    Dim strStockSQL As String
    Dim server As String = "localhost"
    Dim DatabaseName As String = "Gip"
    Dim userName As String = "root"
    Dim password As String = ""
    SQLConnection = New MySqlConnection()
    If Not conn Is Nothing Then conn.Close()
    conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, userName, password, DatabaseName)
    Try

        strStockSQL = "insert into stock (Barcode,Naam_Product,Verkoopprijs) values (@Barcode,@Naam_product,@Verkoopprijs)"
        sqlCommand.Connection = SQLConnection
        sqlCommand.CommandText = strStockSQL
        sqlCommand.Parameters.AddWithValue("@Barcode", Convert.ToString(txtBarcode.Text))
        sqlCommand.Parameters.AddWithValue("@Naam_product", Convert.ToString(txtNaam.Text))
        sqlCommand.Parameters.AddWithValue("@Verkoopprijs", Convert.ToInt32(txtVP.Text))
        sqlCommand.ExecuteNonQuery()

    Catch ex As Exception
        MsgBox("Error occured: Could not insert record")

1 个答案:

答案 0 :(得分:0)

执行sqlCommand时,必须让它的相关连接对象处于打开状态。

SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
SQLConnection.Close()

另外,请阅读Using语句并将其用于SqlConnection

另一件事:此代码行无意义:If Not conn Is Nothing Then conn.Close()将其删除。