I found two different ways to use a transaction from searching the internet.
The first one is using the helper class SqliteTransaction
like below.
SqliteTransaction dbTrans = dbconn.BeginTransaction();
dbCmd.Transaction = dbTrans;
try {
dbCmd.CommandText = "insert into myTable(name, age) values('John', 15)";
dbCmd.ExecuteNonQuery();
dbCmd.CommandText = "insert into myTable(name, age) values('Dave', 23)";
dbCmd.ExecuteNonQuery();
dbCmd.CommandText = "insert into myTable(name, age) values('Bob', 31)";
dbCmd.ExecuteNonQuery();
dbTrans.Commit();
}
catch(Exception e) {
dbTrans.Rollback();
dbTrans.Dispose();
dbCmd.Dispose();
dbConn.Close();
return;
}
dbTrans.Dispose();
dbCmd.Transaction = null;
The other one is just putting SQLite commands directly like this.
dbCmd.CommandText = "begin";
dbCmd.ExecuteNonQuery();
try {
dbCmd.CommandText = "insert into myTable(name, age) values('John', 15)";
dbCmd.ExecuteNonQuery();
dbCmd.CommandText = "insert into myTable(name, age) values('Dave', 23)";
dbCmd.ExecuteNonQuery();
dbCmd.CommandText = "insert into myTable(name, age) values('Bob', 31)";
dbCmd.ExecuteNonQuery();
dbCmd.CommandText = "commit";
dbCmd.ExecuteNonQuery();
}
catch(Exception e) {
dbCmd.CommandText = "rollback";
dbCmd.ExecuteNonQuery();
dbCmd.Dispose();
dbConn.Close();
return;
}
I prefer the latter because it's more simple and I don't have to care about disposing an additional object, but I'm not sure if there are any differences or issues between these.
Both are the same?
Aucun commentaire:
Enregistrer un commentaire