【发布时间】:2021-12-09 18:29:04
【问题描述】:
我需要将一个产品插入到 ProductDB 表中,同时从我刚刚插入的产品中获取 id,所以我可以在下一个查询中将它用作外键我一直在寻找不同的方法,例如“选择 last_insert_rowid()" 和 "SCOPE_IDENTITY()" 但我不能让它工作,我该如何让它工作
public static void SaveProduct(ProductModel product)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("INSERT INTRO ProductDB (Name, Price) VALUES (@Name, @Price);",
product);
string ForeignKey = "the id from the last entry from the query above";
cnn.execute("INSERT INTO ImageDB (Filename, Path, FK_Product) VALUES (@Filename, @Path," + ForeignKey + " )");
}
}
【问题讨论】:
-
这不是关于使用 Visual Studio 的问题,所以我删除了那个标签。
-
见SELECT last_insert_rowid()。您的表当然必须在 ProductDB 表中有一个自动增量字段才能正常工作。
-
另见RETURNING子句