简体   繁体   English

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

[英]vb.net MS Access insert record with auto number primary key column into table with SQL query

I want to insert a new row into a table with a auto number column. 我想在带有自动编号列的表格中插入新行。 My code is below, I can't find out how to insert auto number column simultaneously with other columns: 我的代码在下面,我无法找到如何与其他列同时插入自动编号列:

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

The keyword @@identity does not work; 关键字@@identity无效; what is the proper method? 什么是正确的方法?

If you would have set SQL column to identity auto increment you don't need to pass id parameter while inserting it will automatically work. 如果您将SQL列设置为标识自动递增,则在插入它时会自动运行,而无需传递id参数。

Remove below code: 删除以下代码:

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

Addendum : 附录

Of course, also use: 当然也可以使用:

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

this worked : 这工作:

 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM