Vb.Net获取数据表中的最后一个自动增量值

时间:2014-02-14 13:01:39

标签: vb.net get increment

我从数据表名称car表中加载Access数据库中的数据。此表将carId作为自动递增编号enter image description here

以这种方式加载数据:

Private Sub frmCar_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Try
        dsDataSet = New DataSet
        loadCars()

        bsCar = New BindingSource(dsDataSet, "car")

        CarIDTextBox.DataBindings.Add(New Binding("text", bsCar, "carId"))
        BrandTextBox.DataBindings.Add(New Binding("text", bsCar, "brand"))
        ModelTextBox.DataBindings.Add(New Binding("text", bsCar, "model"))
        RegNoTextBox.DataBindings.Add(New Binding("text", bsCar, "regNo"))
        InsIDTextBox.DataBindings.Add(New Binding("text", bsCar, "insId"))
        DailyChargeTextBox.DataBindings.Add(New Binding("text", bsCar, "dailyCharge"))
        WeeklyChargeTextBox.DataBindings.Add(New Binding("text", bsCar, "weeklyCharge"))
        MonthlyChargeTextBox.DataBindings.Add(New Binding("text", bsCar, "monthlyCharge"))
        YearlyChargeTextBox.DataBindings.Add(New Binding("text", bsCar, "yearlyCharge"))
        TransmissionTextBox.DataBindings.Add(New Binding("text", bsCar, "transmission"))
        ColorTextBox.DataBindings.Add(New Binding("text", bsCar, "color"))
        RemarkTextBox.DataBindings.Add(New Binding("text", bsCar, "remark"))


    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Sub

Sub loadCars()
    Dim sql As String

    Try
        oledbConn = New OleDbConnection(oledbConnString)
        oledbConn.Open()

        sql = "select * from car order by carId"
        daCar = New OleDbDataAdapter(sql, oledbConn)
        daCar.Fill(dsDataSet, "car")
        '----------------------------------------------------------------------

        oledbConn.Close()
    Catch ex As Exception
        oledbConn.Close()
        MsgBox(Err.Description)
    End Try
End Sub

Private Sub btnNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNew.Click
    Try
        bsCar.AddNew()

    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Sub

Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
    Try
        Me.Validate()
        bsCar.EndEdit()
        daCar.Update(dsDataSet.Tables("car"))
        MsgBox("Car saved successfully")
    Catch ex As Exception
        MsgBox(Err.Description)
    End Try
End Sub

现在当我添加一辆新车并保存它时,一切都很完美。但我需要添加的新车的carId在添加后立即显示。如何在不查询数据库的情况下执行此操作?谢谢

1 个答案:

答案 0 :(得分:1)

在执行Update方法期间,似乎有从数据库中获取AutoIncrement值的方法,但是无法避免对数据库进行另一次查询。
更新(或插入)行后,您可以使用OleDbDataAdapter引发的RowUpdated事件。

我们需要使用Access支持的“SELECT @@ IDENTITY”命令,但是如果我们不使用Update使用的相同连接,这可能无效,因此唯一的选择是使用{{1}连接仍处于打开状态的事件

RowUpdated