【发布时间】:2012-08-17 14:40:31
【问题描述】:
可能重复:
SQLite - UPSERT not INSERT or REPLACE
How do I UPDATE a row in a table or INSERT it if it doesn't exist?
我正在使用 Windows 8 发布预览版和 C#(VS 2012) 开发 Metro 应用程序,我是 SQLite 新手,我在我的应用程序中集成了 SQLite 3.7.13,它运行良好,在 MYSQL 中我们喜欢
INSERT INTO tablename (id, name)
VALUES (21, 'foo')
ON DUPLICATE KEY UPDATE name = 'boo';
我们如何在 SQLite 3 中使用 Linq 表达式实现这一点,现在我正在插入记录并捕获 SQLiteException 并在异常时更新该记录。请注意下面的代码
var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,"Student.db");
DateTime LastUpdated = DateTime.UtcNow;
using (var db = new SQLite.SQLiteConnection(dbPath))
{
try
{
db.Insert(new studentRecord() { sid = 21, name = 'foo', last_updated = LastUpdated });
}
catch(SQLite.SQLiteException ex)
{
db.Update(new studentRecord() { sid = 21, name = 'boo', last_updated = LastUpdated });
}
}
studentRecord 是我的表名。
我不确定这是正确的方法,有什么方法可以在单个查询中实现,请帮助我。提前致谢
【问题讨论】:
-
如果抛出另一个异常怎么办?像“连接丢失”之类的东西,当您尝试更新捕获时它会引发另一个错误并且会崩溃,因为您没有尝试捕获它。也许有像你的 mysql 这样更好的方法,但我宁愿检查项目是否已经存在并根据该查询更新或插入。
标签: c# linq sqlite windows-8 windows-runtime