更新值是否已经存在vb以访问数据库

时间:2019-06-03 15:24:53

标签: sql vb.net ms-access oledb

我仍在学习很多有关Visual Basic的知识。现在我发现,与mySQL不同,访问不接受INSERT ... VALUES .... ON DUPLICATE KEY UPDATE ..

现在,我想知道如何才能做到这一点?以下是我的(未清理/脏)代码的一部分。它应该检查是否有重复的“ RentalID”,如果找到了ID,则只能在accdb中更改ID的日期和金额值。

不确定是否有这种方法,如果有更简单的方法,我很乐意学习!

我的代码如下:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim conn As New System.Data.OleDb.OleDbConnection()
        conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='databasefile.accdb'"
        Dim cmd As OleDb.OleDbCommand
        Dim dt As DataTable = New DataTable()
        Dim rentalid = Me.TextBox1.Text
        Dim amount = Me.TextBox3.Text
        Dim date = Me.TextBox4.Text

        Dim SQL As String = "INSERT INTO betaling(rentalID, date, amount) values (@rentalid, @date, @amount);"



        cmd = New OleDb.OleDbCommand(SQL, conn)
        conn.Open()
        Try
            cmd = New OleDb.OleDbCommand
            With cmd
                .Connection = conn
                .CommandType = CommandType.Text
                .CommandText = "INSERT INTO betaling(rentalID, amount, Date) values (@id, @bedrag, @datum);"

                .Parameters.Add(New System.Data.OleDb.OleDbParameter("@rentalid", System.Data.OleDb.OleDbType.VarChar, 255, Me.TextBox1.Text))
                .Parameters.Add(New System.Data.OleDb.OleDbParameter("@amount", System.Data.OleDb.OleDbType.VarChar, 255, Me.TextBox3.Text))
                .Parameters.Add(New System.Data.OleDb.OleDbParameter("@date", System.Data.OleDb.OleDbType.VarChar, 255, Me.TextBox4.Text))


                cmd.Parameters("@id").Value = Me.TextBox1.Text
                cmd.Parameters("@bedrag").Value = Me.TextBox3.Text
                cmd.Parameters("@datum").Value = Me.TextBox4.Text


                cmd.ExecuteNonQuery()
                MsgBox("saved!")

                Me.Close()
                Exit Sub
            End With
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)

        End Try
        Me.Close()
    End Sub```

0 个答案:

没有答案