【问题标题】:Trying to create foreign keys and insert their values in a .mdb database using C# and OleDb尝试使用 C# 和 OleDb 创建外键并将其值插入到 .mdb 数据库中
【发布时间】:2015-05-13 14:23:43
【问题描述】:

我有一个包含 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);
    }
}

(然后是 Table2 的类似内容)。

对于 Table1 中的每一行,我在 Table2 中插入大约 40 行(它们是保存比赛及其参赛者信息的表格)。

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

这就是我迷路的地方。我不知道怎么说“取你刚刚插入Table1的行的id,然后取你刚刚插入Table2的行的id,并将它们作为新记录插入Table3”。

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

【问题讨论】:

    标签: c# ms-access oledb


    【解决方案1】:

    插入一行后,您可以使用SELECT @@Identity 检索自动递增的值。存储它,插入另一行,执行相同的选择,然后将这些值插入到链接表中。

    来自 Microsoft 的更多信息(用于 VB.NET,但易于理解)HOW TO: Retrieve the Identity Value While Inserting Records into Access Database

    【讨论】:

    • 非常感谢!我将解释我如何在我的代码中使用这个答案,以备将来参考,以防任何人从中受益:我创建了一个新的 OleDbCommand 对象来检索自动递增的值:OleDbCommand identity = new OleDbCommand(); identity.Connection = dbConnection; 然后我添加了查询:@987654324 @ 然后,我没有使用 ExecuteNonQuery(),因为我只想要返回 1 列,所以我使用了 ExecuteScalar():string id = Convert.ToString(identity.ExecuteScalar()); 和 ta-da! “id”变量现在保存我刚刚插入的记录的 id。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 2012-01-24
    • 2018-11-25
    • 2011-08-05
    • 1970-01-01
    相关资源
    最近更新 更多