vb.net MS Access使用SQL查询将具有自动编号主键列的记录插入表

时间:2019-01-02 09:26:12

标签: sql vb.net ms-access autonumber

我想在带有自动编号列的表格中插入新行。我的代码在下面,我无法找出如何同时插入自动编号列和其他列:

pth = My.Application.Info.DirectoryPath

Dim SQL = "INSERT INTO approved (id, word, approveds) VALUES (@idd, @word, @approval)"

Using Con As New OleDbConnection("Provider=Microsoft.ace.oledb.12.0; Data Source=" & pth & "\database.mdb; User Id=; Password=;")
    Dim Cmd As New OleDbCommand(SQL, Con)

    Cmd.Parameters.Add("@idd", OleDb.OleDbType.VarChar).Value = @@identity
    Cmd.Parameters.Add("@word", OleDb.OleDbType.VarChar).Value = RichTextBox1.SelectedText
    Cmd.Parameters.Add("@approval", OleDb.OleDbType.VarChar).Value = "YES"

    Con.Open()
    Cmd.ExecuteNonQuery()
End Using

关键字@@identity无效;正确的方法是什么?

2 个答案:

答案 0 :(得分:0)

如果您将SQL列设置为标识自动增量,则在插入ID参数将自动起作用时不需要传递id参数。

删除以下代码:

Cmd.Parameters.Add("@idd", OleDb.OleDbType.VarChar).Value = @@identity

附录

当然也可以使用:

Dim SQL = "insert into approved (word, approveds) VALUES (@word, @approval)"

答案 1 :(得分:0)

这有效:

 pth = My.Application.Info.DirectoryPath



            Dim SQL = "insert into approved (word, approveds) VALUES (@word, @approval)"
            Using Con As New OleDbConnection("Provider=Microsoft.ace.oledb.12.0; Data Source=" & pth & "\database.mdb; User Id=; Password=;")
                Dim Cmd As New OleDbCommand(SQL, Con)

                Cmd.Parameters.Add("@word", OleDb.OleDbType.VarChar).Value = RichTextBox1.SelectedText
                Cmd.Parameters.Add("@approval", OleDb.OleDbType.VarChar).Value = "YES"
                Con.Open()
                Cmd.ExecuteNonQuery()
            End Using