如何将自动递增数据类型插入另一个 table c#

how to insert the auto increment data type to another table c#

我想将增量 ID PRIMARY KEY 添加到另一个 TABLE

这是我的代码

           int id = null; //this id is public

            OleDbCommand command = new OleDbCommand("insert into Table1([ID], [Name] values (@ID, @Name)", connection);
            command.Parameters.AddWithValue("@ID", id);
            command.Parameters.AddWithValue("@ID", txtName.Text);
            command.ExecuteNonQuery();
            command.Parameters.Clear();

添加到这个数据库 add to this database

            OleDbCommand command2 = new OleDbCommand("insert into Table2([TableID], [OtherInfo], [OtherDocument] values (@TableID, @OtherInfo, @OtherDocument)", connection);
            command2.Parameters.AddWithValue("@TableIDID", id);
            command2.Parameters.AddWithValue("@OtherInfo", txtOtherInfo.Text);
            command2.Parameters.AddWithValue("@OtherDocument", txtOtherDocument.Text);
            command2.ExecuteNonQuery();
            command2.Parameters.Clear();
    

TAble2

我希望每次我添加一个新名称时,id 字段也添加其他 table 抱歉我的英语不好谢谢。

因为你的 ID 字段是一个自动编号,你不应该在插入时为其赋值,你让数据库为你创建它

OleDbCommand command = new OleDbCommand("insert into Table1([Name] values ( @Name)", connection);

command.Parameters.AddWithValue("@Name", txtName.Text);
command.ExecuteNonQuery();

现在的问题是如何找回它。这可以使用命令 SELECT @@IDENTITY

来完成
command.Parameters.Clear();
command.CommandText = "SELECT @@IDENTITY";
int id = Convert.ToInt32(command.ExecuteScalar());

最后,您可以将在您的插页上检索到的 ID 用于另一个 table,

这是 MS-Access 不理解批处理命令所需的模式。其他数据库系统对此有更好的模式,只访问一次数据库而不是两次。 (当然,Access主要是桌面数据库,这没什么区别)