BeginTransaction() Method
Begins a database transaction.
|
|---|
'Declaration
Public Overloads Shadows Function BeginTransaction() As SQLiteTransaction |
Return Value
An object representing the new transaction.
The following example creates a
SQLiteConnection and a
SQLiteTransaction. It also demonstrates how to use the
BeginTransaction(),
Commit, and
Rollback methods.
|
|---|
public void RunSQLiteTransaction(string myConnString)
{
SQLiteConnection sqLiteConnection = new SQLiteConnection(myConnString);
sqLiteConnection.Open();
SQLiteCommand sqLiteCommand = new SQLiteCommand();
sqLiteCommand.Connection = sqLiteConnection;
SQLiteTransaction myTrans;
// Start a local transaction
myTrans = sqLiteConnection.BeginTransaction();
// Assign transaction object for a pending local transaction
sqLiteCommand.Transaction = myTrans;
try
{
sqLiteCommand.CommandText = "INSERT INTO Dept(DeptNo, DName) Values(50, 'DEVELOPMENT')";
sqLiteCommand.ExecuteNonQuery();
sqLiteCommand.CommandText = "INSERT INTO Dept(DeptNo, DName) Values(60, 'PRODUCTION')";
sqLiteCommand.ExecuteNonQuery();
myTrans.Commit();
Console.WriteLine("Both records are written to database.");
}
catch(Exception e)
{
myTrans.Rollback();
Console.WriteLine(e.ToString());
Console.WriteLine("Neither record was written to database.");
}
finally
{
sqLiteConnection.Close();
}
} |
|
|---|
Public Sub RunSQLiteTransaction(myConnString As String)
Dim sqLiteConnection As New SQLiteConnection(myConnString)
sqLiteConnection.Open()
Dim sqLiteCommand As New SQLiteCommand()
sqLiteCommand.Connection = sqLiteConnection
Dim myTrans As SQLiteTransaction
' Start a local transaction
myTrans = sqLiteConnection.BeginTransaction()
' Assign transaction object for a pending local transaction
sqLiteCommand.Transaction = myTrans
Try
sqLiteCommand.CommandText = "INSERT INTO Dept(DeptNo, DName) Values(50, 'DEVELOPMENT')"
sqLiteCommand.ExecuteNonQuery()
sqLiteCommand.CommandText = "INSERT INTO Dept(DeptNo, DName) Values(60, 'PRODUCTION')"
sqLiteCommand.ExecuteNonQuery()
myTrans.Commit()
Console.WriteLine("Both records are written to database.")
Catch e As Exception
myTrans.Rollback()
Console.WriteLine(e.ToString())
Console.WriteLine("Neither record was written to database.")
Finally
sqLiteConnection.Close()
End Try
End Sub |