【发布时间】: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?
【问题讨论】: