如何将自动递增数据类型插入到另一个表 C#



我想将增量 ID 主键添加到另一个表

这是我的代码

           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();

添加到此数据库添加到此数据库

            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();
    

标签2

我希望每次我添加一个新名称时,id 字段也会在其他表中添加对不起我的英语不好谢谢。

因为您的 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 用于其他表,

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

最新更新