UWP将sqlite插入查询包装到sql事务中

时间:2016-02-16 14:10:39

标签: c# visual-studio sqlite win-universal-app

我正在尝试将一些csv样式的file.txt内容插入到本地SQLite数据库中,我处理文件读取,内容处理并获取一些字符串:

INSERT OR REPLACE INTO mytab (id,name,adress) VALUES(1,john,adress1)
INSERT OR REPLACE INTO mytab (id,name,adress) VALUES(2,marry,adress2)
INSERT OR REPLACE INTO mytab (id,name,adress) VALUES(3,lama,ruadress3)
//...

现在我想打开一个sqlite事务,执行所有这些插入然后关闭事务。我正在使用SQLite.Net-PCLSQLite for Universal App Platform,我该怎么做?

我试图打开这样的连接:

var sqlpath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "Mydb.sqlite");
SQLiteConnection conn = new SQLiteConnection(new SQLitePlatformWinRT(), sqlpath);

//I'am trying to open transaction - but get ERROR -> SQLiteCommand does not contain contstructor that takes 2 arguments
 SQLiteCommand cmd = new SQLiteCommand("BEGIN", conn);

1 个答案:

答案 0 :(得分:2)

SQLiteConnection中的SQLite.Net-PCL类有BeginTransactionCommitRollback方法,因此您可以在BeginTransaction和Commit之间包装命令:

// Open connection
SQLiteConnection conn = new SQLiteConnection(new SQLitePlatformWinRT(), sqlpath);
try {
   // Start transaction
   conn.BeginTransaction();
   try {
      // Execute commands...
      // Commit transaction
      conn.Commit();
   }
   catch (Exception) {
      // Rollback transaction
      conn.Rollback();
   }
}
finally {
   // Close connection
   conn.Close();
}