尝试使用 C# 和 OleDb 创建外键并将它们的值插入到 .mdb 数据库中

Trying to create foreign keys and insert their values in a .mdb database using C# and OleDb

我有一个包含 3 个表的数据库。其中一个与其他两个保持关系。例如:

Table1 = idTable1 (PK_Table1), attribute1, attribute2, attribute3

Table2 = idTable2 (PK_Table2), attribute1

Table3 = idTable3 (PK_Table3), attribute1 (FK relating to idTable1), attribute2 (FK relating to idTable2)

所有主键都是由 Access(2002 版本,这就是为什么我的数据库是 .mdb)自动分配的自动递增字段。

在我的代码中,我使用如下代码在 Table1 和 Table2 中插入数据:

public void insert()
{
    string query = "INSERT INTO Table1 (attribute1,attribute2,attribute3) VALUES (?,?,?)";
    OleDbConnection dbConnection = new OleDbConnection();
    dbConnection.ConnectionString = connStr;
    try
    {
        dbConnection.Open();
        OleDbCommand commandStatement = new OleDbCommand();
        OleDbCommand primarykey = new OleDbCommand("ALTER TABLE Table1 ADD CONSTRAINT pk_Table1 primary key(idTable1)", dbConnection);
        primarykey.Connection = dbConnection;

        commandStatement.Connection = dbConnection;
        commandStatement.CommandText = query;
        commandStatement.Parameters.Add("attribute1", OleDbType.Integer).Value = attribute1;                
                commandStatement.Parameters.Add("attribute2", OleDbType.Integer).Value = attribute2;
        commandStatement.Parameters.Add("attribute3", OleDbType.Integer).Value = attribute3;

        commandStatement.ExecuteNonQuery();
        primarykey.ExecuteNonQuery(); 
        dbConnection.Close();
        dbConnection.Dispose();
        commandStatement.Dispose();
                primarykey.Dispose();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
}

(然后表 2 也有类似的东西)。

对于表 1 中的每一行,我在表 2 中插入了大约 40 行(它们是包含比赛及其参赛者信息的表)。

现在我需要使用 Table3 在这两者之间创建关系,它必须引用两个表的 ID 作为外键。

这就是我迷路的地方。我不知道怎么说 "take the id of the row you just inserted in Table1 and then the id of a row you just inserted in Table2 and insert them as a new record in Table3".

有没有办法在我插入记录后立即获取数据库分配的自动递增 ID?

插入行后,您可以使用 SELECT @@Identity 检索自动递增的值。存储它,插入另一行,执行相同的操作 select 然后将这些值插入到 link table.

来自 Microsoft HOW TO: Retrieve the Identity Value While Inserting Records into Access Database

的更多信息(针对 VB.NET,但易于理解)