本文整理汇总了C#中Mono.Data.Sqlite.SqliteConnection.BeginTransaction方法的典型用法代码示例。如果您正苦于以下问题:C# SqliteConnection.BeginTransaction方法的具体用法?C# SqliteConnection.BeginTransaction怎么用?C# SqliteConnection.BeginTransaction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Mono.Data.Sqlite.SqliteConnection
的用法示例。
在下文中一共展示了SqliteConnection.BeginTransaction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ExcuteTransaction
public bool ExcuteTransaction(string sql)
{
var cmds = sql.Split(';');
using (SqliteConnection conn = new SqliteConnection(this.SqlConfig.ConnectionString))
{
conn.Open();
SqliteCommand cmd = new SqliteCommand(conn);
SqliteTransaction tran = conn.BeginTransaction();
try
{
foreach (var cmdSql in cmds)
{
cmd.CommandText = cmdSql;
cmd.ExecuteNonQuery();
}
tran.Commit();
conn.Close();
return true;
}
catch (Exception e)
{
tran.Rollback();
conn.Close();
throw new Exception(e.Message + " sql:" + sql);
}
finally
{
conn.Close();
}
}
}
示例2: SQLiteEnlistment
internal SQLiteEnlistment(SqliteConnection cnn, Transaction scope)
{
_transaction = cnn.BeginTransaction();
_scope = scope;
_disposeConnection = false;
_scope.EnlistVolatile(this, System.Transactions.EnlistmentOptions.None);
}
示例3: AddNewUploadEntry
public void AddNewUploadEntry(UploadEntry uploadentry)
{
using (SqliteConnection conn = new SqliteConnection(_connectionString))
{
conn.Open();
using (SqliteTransaction trans = conn.BeginTransaction())
{
using (SqliteCommand cmd = conn.CreateCommand())
{
cmd.Transaction = trans;
cmd.CommandText = @"UPDATE UploadEntries SET Cancelled = 1 WHERE Name = @name";
cmd.Parameters.Add(new SqliteParameter("@name", uploadentry.Name));
cmd.ExecuteNonQuery(); //TODO: log here how many other entries were cancelled.
cmd.CommandText = @"INSERT INTO UploadEntries(
Name,
Size,
CleanedName,
ObscuredName,
RemoveAfterVerify,
CreatedAt,
UploadedAt,
NotifiedIndexerAt,
SeenOnIndexerAt,
Cancelled)
VALUES(
@name,
@size,
@cleanedName,
@ObscuredName,
@removeAfterVerify,
@createdAt,
@uploadedAt,
@notifiedIndexerAt,
@seenOnIndexerAt,
@cancelled)";
cmd.Parameters.Add(new SqliteParameter("@name", uploadentry.Name));
cmd.Parameters.Add(new SqliteParameter("@size", uploadentry.Size));
cmd.Parameters.Add(new SqliteParameter("@cleanedName", uploadentry.CleanedName));
cmd.Parameters.Add(new SqliteParameter("@ObscuredName", uploadentry.ObscuredName));
cmd.Parameters.Add(new SqliteParameter("@removeAfterVerify", uploadentry.RemoveAfterVerify));
cmd.Parameters.Add(new SqliteParameter("@createdAt", GetDbValue(uploadentry.CreatedAt)));
cmd.Parameters.Add(new SqliteParameter("@uploadedAt", GetDbValue(uploadentry.UploadedAt)));
cmd.Parameters.Add(new SqliteParameter("@notifiedIndexerAt", GetDbValue(uploadentry.NotifiedIndexerAt)));
cmd.Parameters.Add(new SqliteParameter("@seenOnIndexerAt", GetDbValue(uploadentry.SeenOnIndexAt)));
cmd.Parameters.Add(new SqliteParameter("@cancelled", GetDbValue(uploadentry.Cancelled)));
cmd.ExecuteNonQuery();
cmd.CommandText = "select last_insert_rowid()";
cmd.Parameters.Clear();
uploadentry.ID = (Int64)cmd.ExecuteScalar();
}
trans.Commit();
}
}
}
示例4: RunTests
public static void RunTests(string dbPath)
{
using (var cnn = new SqliteConnection("Data Source=" + dbPath))
{
cnn.Open();
// commit
using (var trn = cnn.BeginTransaction(IsolationLevel.Serializable))
using (var cmd = new SqliteCommand("CREATE TABLE IF NOT EXISTS nugettest (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT);", cnn))
{
cmd.ExecuteNonQuery();
cmd.CommandText = "DELETE FROM nugettest;";
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO nugettest (data) VALUES (@someData);";
cmd.Parameters.AddWithValue("@someData", "data here");
cmd.ExecuteNonQuery();
trn.Commit();
}
// rollback
using (var trn = cnn.BeginTransaction(IsolationLevel.Serializable))
using (var cmd = new SqliteCommand("INSERT INTO nugettest (data) VALUES (@someData);", cnn))
{
cmd.Parameters.AddWithValue("@someData", "data here");
cmd.ExecuteNonQuery();
trn.Rollback();
}
// check
using (var cmd = new SqliteCommand("SELECT COUNT(*) nugettest;", cnn))
{
if (Convert.ToInt32(cmd.ExecuteScalar()) != 1)
{
throw new Exception("Something bad happened!");
}
}
}
}
示例5: SaveItems
public void SaveItems(List<Item> newItems)
{
// There may be zero items, so only call this once to avoid 300+ select queries when the cache is empty.
List<Item> allItems = Repository.Default.ListItems().ToList();
using (SqliteConnection connection = new SqliteConnection(Repository.Default.ItemsConnectionString))
{
connection.Open();
SqliteRepository repository = (SqliteRepository)Repository.Default;
// Perform the inserts inside a transaction to avoid the journal file being constantly opened + closed.
using (SqliteTransaction transaction = connection.BeginTransaction())
{
SqliteCommand command = new SqliteCommand(connection);
command.Transaction = transaction;
List<Item> addItems = new List<Item>();
bool hasItems = allItems.Count > 0;
foreach (Item item in newItems)
{
// if (hasItems)
// {
//
// }
// else
// {
//
// }
// Check for duplicates in memory
if (!addItems.Any(i => i.Equals(item)) && !allItems.Any(i => i.Equals(item)))
{
repository.SaveItemForTransaction(command, item);
addItems.Add(item);
}
OnFeedSaved(EventArgs.Empty);
}
try
{
transaction.Commit();
ItemCache.Current.Clear();
Settings.Current.LastUpdate = DateTime.Now;
}
catch (SqliteException e)
{
Logger.Warn("An error occured committing the save transaction on new items:{0}", e);
transaction.Rollback();
}
}
}
}
示例6: ExecuteQuery
public void ExecuteQuery(CallbackQuery callback)
{
using (var conn = new SqliteConnection("Data Source=" + filename))
{
conn.Open();
using (SqliteTransaction transaction = conn.BeginTransaction())
{
using (SqliteCommand command = conn.CreateCommand())
{
callback(command);
}
transaction.Commit();
}
conn.Close();
}
}
示例7: Command
/// <summary>
/// 执行sql语句
/// </summary>
/// <param name="DB">数据库</param>
/// <param name="SQLs">sql语句</param>
/// <returns>返回影响行数</returns>
public static int Command(string DB, params string[] SQLs)
{
int result = 0;
if ( File.Exists(DB) && SQLs != null )
{
using ( SQLiteConnection con = new SQLiteConnection(@"Data Source=" + DB) )
{
con.Open();
using ( SQLiteTransaction trans = con.BeginTransaction() )
{
try
{
using ( SQLiteCommand cmd = new SQLiteCommand(con) )
{
foreach ( string SQLstr in SQLs )
{
cmd.CommandText = SQLstr;
result += cmd.ExecuteNonQuery();
}
}
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
trans.Rollback();//出错,回滚
result = -1;
}
finally
{
try{
trans.Commit();
}catch{ }
}
}
con.Close();
}
}
return result;
}
示例8: DeleteProfiles
////////////////////////////////////////////////////////
// Mangement APIs from ProfileProvider class //
//----------------------------------------------------//
////////////////////////////////////////////////////////
// Delete Profiles //
//----------------------------------------------------//
public override int DeleteProfiles(ProfileInfoCollection profiles)
{
SqliteConnection holder = new SqliteConnection(_connectionString);
SqliteTransaction trans = null;
if (profiles == null)
{
throw new ArgumentNullException("profiles");
}
if (profiles.Count < 1)
{
throw new ArgumentException("Profiles collection is empty", "profiles");
}
foreach (ProfileInfo pi in profiles)
{
string username = pi.UserName;
//SecUtility.CheckParameter(ref username, true, true, true, 255, "UserName");
}
try
{
bool fBeginTransCalled = false;
int numDeleted = 0;
try
{
holder.Open();
trans = holder.BeginTransaction();
fBeginTransCalled = true;
int appId = GetApplicationId(holder);
foreach (ProfileInfo profile in profiles)
if (DeleteProfile(holder, profile.UserName.Trim(), appId))
numDeleted++;
trans.Commit();
fBeginTransCalled = false;
}
catch (Exception e)
{
if (WriteExceptionsToEventLog)
{
WriteToEventLog(e, "Delete Profile");
throw new ProviderException(exceptionMessage);
}
else
{
throw e;
}
}
finally
{
if (fBeginTransCalled)
{
try
{
trans.Rollback();
}
catch { }
}
holder.Close();
}
return numDeleted;
}
catch
{
throw;
}
}
示例9: LoadData
/// <summary>
/// load data from a CSV file in Postgresql COPY format
/// </summary>
static private bool LoadData(TDataDefinitionStore ADataDefinition, SqliteConnection conn, string APath, string ATablename)
{
using (SqliteTransaction dbTrans = conn.BeginTransaction())
{
using (SqliteCommand cmd = conn.CreateCommand())
{
TTable table = ADataDefinition.GetTable(ATablename);
StringCollection ColumnNames = new StringCollection();
foreach (TTableField f in table.grpTableField)
{
ColumnNames.Add(f.strName);
}
// prepare the statement
PrepareSqlStatement(cmd, ATablename, table, ColumnNames);
// load the data from the text file
string filename = APath + Path.DirectorySeparatorChar + ATablename + ".csv";
if (File.Exists(filename + ".local"))
{
filename += ".local";
}
StreamReader reader = new StreamReader(filename);
string line;
while ((line = reader.ReadLine()) != null)
{
ProcessLine(cmd, line, table, ColumnNames);
if (cmd.ExecuteNonQuery() != 1)
{
throw new Exception("failed to import line for table " + ATablename);
}
}
}
dbTrans.Commit();
}
return true;
}
示例10: LoadDataFromReader
/// <summary>
/// load data from the sql file in Postgresql COPY format
/// </summary>
static private bool LoadDataFromReader(TDataDefinitionStore ADataDefinition,
SqliteConnection conn,
StreamReader sr,
string ATablename,
StringCollection AColumnNames)
{
using (SqliteTransaction dbTrans = conn.BeginTransaction())
{
using (SqliteCommand cmd = conn.CreateCommand())
{
TTable table = ADataDefinition.GetTable(ATablename);
// prepare the statement
PrepareSqlStatement(cmd, ATablename, table, AColumnNames);
string line;
while ((line = sr.ReadLine()) != "\\.")
{
ProcessLine(cmd, line, table, AColumnNames);
cmd.ExecuteNonQuery();
}
}
dbTrans.Commit();
}
return true;
}
示例11: DeleteRole
/// <summary>
/// RoleProvider.DeleteRole
/// </summary>
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
if (!RoleExists(roleName))
{
throw new ProviderException(string.Format(Properties.Resources.ErrRoleNotExist, roleName));
}
if (throwOnPopulatedRole && GetUsersInRole(roleName).Length > 0)
{
throw new ProviderException(Properties.Resources.ErrCantDeletePopulatedRole);
}
using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
{
using (SqliteCommand dbCommand = dbConn.CreateCommand())
{
dbCommand.CommandText = string.Format("DELETE FROM \"{0}\" WHERE \"Rolename\" = @Rolename AND \"ApplicationName\" = @ApplicationName", m_RolesTableName);
AddParameter (dbCommand, "@Rolename", roleName);
AddParameter (dbCommand, "@ApplicationName", m_ApplicationName);
SqliteTransaction dbTrans = null;
try
{
dbConn.Open();
dbCommand.Prepare();
using (dbTrans = dbConn.BeginTransaction())
{
dbCommand.ExecuteNonQuery();
// Attempt to commit the transaction
dbTrans.Commit();
}
}
catch (SqliteException e)
{
Trace.WriteLine(e.ToString());
try
{
// Attempt to roll back the transaction
Trace.WriteLine(Properties.Resources.LogRollbackAttempt);
dbTrans.Rollback();
}
catch (SqliteException re)
{
// Rollback failed
Trace.WriteLine(Properties.Resources.ErrRollbackFailed);
Trace.WriteLine(re.ToString());
}
throw new ProviderException(Properties.Resources.ErrOperationAborted);
}
finally
{
if (dbConn != null)
dbConn.Close();
}
}
}
return true;
}
示例12: UpdateResetRowErrorCorrectly
[Category ("NotWorking")] // Requires newer sqlite than is on wrench
public void UpdateResetRowErrorCorrectly ()
{
const string connectionString = "URI = file::memory:; Version = 3";
using (var dbConnection = new SqliteConnection (connectionString)) {
dbConnection.Open ();
using (var cmd = dbConnection.CreateCommand ()) {
cmd.CommandText = "CREATE TABLE data (id PRIMARY KEY, name TEXT)";
cmd.ExecuteNonQuery ();
}
var ts = dbConnection.BeginTransaction ();
var da = new SqliteDataAdapter ("SELECT * FROM data", dbConnection);
var builder = new SqliteCommandBuilder (da);
da.UpdateCommand = builder.GetUpdateCommand ();
da.UpdateCommand.Transaction = ts;
var ds1 = new DataSet ();
da.Fill (ds1, "data");
var table = ds1.Tables [0];
var row = table.NewRow ();
row ["id"] = 10;
row ["name"] = "Bart";
table.Rows.Add (row);
var ds2 = ds1.GetChanges ();
da.Update (ds2, "data");
Assert.IsFalse (ds2.HasErrors);
}
}
示例13: ConvertFrom101
//.........这里部分代码省略.........
byte[] bytes = Sqlite3.sqlite3_column_rawbytes(Stmt, 1);
if (bytes != null)
data.str1 = UTF8.GetString(Encoding.Convert(CP1252, UTF8, bytes));
else
data.str1 = "Someone";
bytes = Sqlite3.sqlite3_column_rawbytes(Stmt, 2);
if (bytes != null)
data.str2 = UTF8.GetString(Encoding.Convert(CP1252, UTF8, bytes));
else
data.str2 = "Someone";
songs.Add(data);
}
Sqlite3.sqlite3_finalize(Stmt);
}
Stmt = new Sqlite3.Vdbe();
if (!dateExists)
res = Sqlite3.sqlite3_prepare_v2(OldDB, "SELECT id, PlayerName FROM Scores", -1, ref Stmt, 0);
else
res = Sqlite3.sqlite3_prepare_v2(OldDB, "SELECT id, PlayerName, Date FROM Scores", -1, ref Stmt, 0);
if (res != Sqlite3.SQLITE_OK)
{
CLog.LogError("Error query Database: " + FilePath + " (" + Sqlite3.sqlite3_errmsg(OldDB) + ")");
}
else
{
//Sqlite3.sqlite3_step(Stmt);
Encoding UTF8 = Encoding.UTF8;
Encoding CP1252 = Encoding.GetEncoding(1252);
while (Sqlite3.sqlite3_step(Stmt) == Sqlite3.SQLITE_ROW)
{
SData data = new SData();
data.id = Sqlite3.sqlite3_column_int(Stmt, 0);
byte[] bytes = Sqlite3.sqlite3_column_rawbytes(Stmt, 1);
if (bytes != null)
data.str1 = UTF8.GetString(Encoding.Convert(CP1252, UTF8, bytes));
else
data.str1 = "Someone";
if (dateExists)
data.ticks = UnixTimeToTicks(Sqlite3.sqlite3_column_int(Stmt, 2));
scores.Add(data);
}
Sqlite3.sqlite3_finalize(Stmt);
}
}
Sqlite3.sqlite3_close(OldDB);
SQLiteTransaction _Transaction = connection.BeginTransaction();
// update Title and Artist strings
foreach (SData data in songs)
{
command.CommandText = "UPDATE Songs SET [Artist] = @artist, [Title] = @title WHERE [ID] = @id";
command.Parameters.Add("@title", System.Data.DbType.String, 0).Value = data.str2;
command.Parameters.Add("@artist", System.Data.DbType.String, 0).Value = data.str1;
command.Parameters.Add("@id", System.Data.DbType.Int32, 0).Value = data.id;
command.ExecuteNonQuery();
}
// update player names
foreach (SData data in scores)
{
if (!dateExists)
command.CommandText = "UPDATE Scores SET [PlayerName] = @player WHERE [id] = @id";
else
{
command.CommandText = "UPDATE Scores SET [PlayerName] = @player, [Date] = @date WHERE [id] = @id";
command.Parameters.Add("@date", System.Data.DbType.Int64, 0).Value = data.ticks;
}
command.Parameters.Add("@player", System.Data.DbType.String, 0).Value = data.str1;
command.Parameters.Add("@id", System.Data.DbType.Int32, 0).Value = data.id;
command.ExecuteNonQuery();
}
_Transaction.Commit();
//Delete old tables after conversion
command.CommandText = "DROP TABLE US_Scores;";
command.ExecuteNonQuery();
command.CommandText = "DROP TABLE US_Songs;";
command.ExecuteNonQuery();
reader.Dispose();
command.Dispose();
connection.Close();
connection.Dispose();
return true;
}
示例14: ConvertFrom110
/// <summary>
/// Converts a USDX 1.1 database into the Vocaluxe format
/// </summary>
/// <param name="FilePath">Database file path</param>
/// <returns>True if succeeded</returns>
private static bool ConvertFrom110(string FilePath)
{
SQLiteConnection connection = new SQLiteConnection();
connection.ConnectionString = "Data Source=" + FilePath;
SQLiteCommand command;
try
{
connection.Open();
}
catch (Exception)
{
return false;
}
command = new SQLiteCommand(connection);
//The USDX database has no column for LineNr, Medley and Duet so just fill 0 in there
command.CommandText = "INSERT INTO Scores (SongID, PlayerName, Score, LineNr, Date, Medley, Duet, Difficulty) SELECT SongID, Player, Score, '0', Date, '0', '0', Difficulty from US_Scores";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO Songs SELECT ID, Artist, Title, TimesPlayed from US_Songs";
command.ExecuteNonQuery();
List<SData> scores = new List<SData>();
List<SData> songs = new List<SData>();
SQLiteDataReader reader = null;
command.CommandText = "SELECT id, PlayerName, Date FROM Scores";
try
{
reader = command.ExecuteReader();
}
catch (Exception)
{
throw;
}
if (reader != null && reader.HasRows)
{
while (reader.Read())
{
SData data = new SData();
data.id = reader.GetInt32(0);
data.str1 = reader.GetString(1);
data.ticks = UnixTimeToTicks((int)reader.GetInt64(2));
scores.Add(data);
}
reader.Close();
}
command.CommandText = "SELECT id, Artist, Title FROM Songs";
try
{
reader = command.ExecuteReader();
}
catch (Exception)
{
throw;
}
if (reader != null && reader.HasRows)
{
while (reader.Read())
{
SData data = new SData();
data.id = reader.GetInt32(0);
data.str1 = reader.GetString(1);
data.str2 = reader.GetString(2);
songs.Add(data);
}
reader.Close();
}
reader.Dispose();
SQLiteTransaction _Transaction = connection.BeginTransaction();
// update Title and Artist strings
foreach (SData data in songs)
{
command.CommandText = "UPDATE Songs SET [Artist] = @artist, [Title] = @title WHERE [ID] = @id";
command.Parameters.Add("@title", System.Data.DbType.String, 0).Value = data.str2;
command.Parameters.Add("@artist", System.Data.DbType.String, 0).Value = data.str1;
command.Parameters.Add("@id", System.Data.DbType.Int32, 0).Value = data.id;
command.ExecuteNonQuery();
}
// update player names
foreach (SData data in scores)
{
command.CommandText = "UPDATE Scores SET [PlayerName] = @player, [Date] = @date WHERE [id] = @id";
command.Parameters.Add("@player", System.Data.DbType.String, 0).Value = data.str1;
command.Parameters.Add("@date", System.Data.DbType.Int64, 0).Value = data.ticks;
command.Parameters.Add("@id", System.Data.DbType.Int32, 0).Value = data.id;
//.........这里部分代码省略.........
示例15: RunCommand
static private void RunCommand(SqliteConnection conn, string deletestmt)
{
using (SqliteTransaction dbTrans = conn.BeginTransaction())
{
using (SqliteCommand cmd = conn.CreateCommand())
{
cmd.CommandText = deletestmt;
cmd.ExecuteNonQuery();
}
dbTrans.Commit();
}
}