public void BackupDatabaseToFile(string filePath) { //https://stackoverflow.com/questions/11383775/memory-stream-as-db/11385280 SQLiteConnection fileConnection = new SQLiteConnection($"Data Source={filePath};Version=3;"); fileConnection.Open(); _connection.BackupDatabase(fileConnection, "main", "main", -1, null, 0); fileConnection.Close(); }
public static bool InitializeDatabase() { bool exists = false; m_dbConnection = new SQLiteConnection("Data Source=:memory:; PRAGMA synchronous=OFF; PRAGMA journal_mode=MEMORY"); m_dbConnection.Open(); string sourcePath = "Content\\WinShooterGame.sqlite"; string savePath = "Content\\save.sqlite"; /* * if (File.Exists(savePath)) * { * sourcePath = savePath; * exists = true; * } */ using (SQLiteConnection source = new SQLiteConnection("Data Source=" + sourcePath)) { source.Open(); source.BackupDatabase(m_dbConnection, "main", "main", -1, null, 0); } return(exists); }
public static void takeBackup() { try { var saveFileDialog1 = new System.Windows.Forms.SaveFileDialog(); saveFileDialog1.Filter = "DataBase Backup|*.db"; saveFileDialog1.Title = "Save an Backup File"; saveFileDialog1.FileName = "data" + DateTime.Now.ToShortDateString().Replace("/", "-"); if (saveFileDialog1.ShowDialog() != System.Windows.Forms.DialogResult.Cancel && saveFileDialog1.FileName != "") { using (var source = new SQLiteConnection(@"Data Source=|DataDirectory|\data.db; Version=3;")) using (var destination = new SQLiteConnection("Data Source=" + saveFileDialog1.FileName + "; Version=3;")) { source.Open(); destination.Open(); source.BackupDatabase(destination, "main", "main", -1, null, 0); } MainWindow.main.showGrowlNotification(Backup_KEY, true, "پشتیبان گیری از اطلاعات "); } } catch (Exception) { MainWindow.main.showGrowlNotification(Backup_KEY, false, "پشتیبان گیری از اطلاعات "); } }
/// <summary> /// 使用内存数据库 /// </summary> public void MemoryDatabaseEnable() { try { if (_connectionMemory == null) { _connectionMemory = new SQLiteConnection("Data Source = :memory:"); _connectionCurrent = _connectionMemory; _connectionMemory.Open(); // allways open if (_connectionDisk == null) { _connectionDisk = new SQLiteConnection(ConnectionString); } if (_connectionDisk.State != ConnectionState.Open) { _connectionDisk.Open(); } _connectionDisk.BackupDatabase(_connectionMemory, "main", "main", -1, null, -1); _connectionDisk.Close(); StartWriteDbThread(); } } catch (Exception) { throw; } }
public static void Backups(string backupsaddress) { try { string strConnection = ConfigurationManager.ConnectionStrings["SqliteConnection"].ConnectionString; string backupsconnstr = string.Format(strConnection, backupsaddress); string currentconnstr = string.Format(strConnection, _DbFilePath); using (SQLiteConnection currentconn = new SQLiteConnection(currentconnstr)) { using (SQLiteConnection backupsconn = new SQLiteConnection(backupsconnstr)) { currentconn.Open(); backupsconn.Open(); currentconn.BackupDatabase(backupsconn, "main", "main", -1, null, 0); currentconn.Close(); currentconn.Close(); } } } catch (Exception ex) { throw ex; } }
internal static bool BackupDatabase(string DBLocation, string BackupDBName, out SQLiteErrorCode returnCode) { SQLiteConnection conn = null; SQLiteCommand cmd = null; SQLiteConnection connDest = new SQLiteConnection(); SQLiteCommand cmdDest = null; returnCode = SQLiteErrorCode.Ok; if (!OpenDB(DBLocation, ref conn, ref cmd, out returnCode)) { return(false); } if (!OpenDB(BackupDBName, ref connDest, ref cmdDest, out returnCode)) { CloseDB(conn); return(false); } try { bCancelBackup = false; conn.BackupDatabase(connDest, "main", "main", 80, BackupCallback, 1000); return(true); } catch (Exception ex) { LastError = ex.Message; returnCode = conn.ExtendedResultCode(); return(false); } finally { CloseDB(conn); CloseDB(connDest); } }
public void TestTableSchemas() { List <IDomainTable> tablesToCreate = new List <IDomainTable>(); tablesToCreate.Add(new InfoTable()); using (IDbConnection db = ":memory:".OpenDbConnection()) { foreach (ICreatableDomainTable table in tablesToCreate) { Assert.IsTrue(table.Create(db), "Create return false"); int retVal = table.Create_Index(db); //TraceLibrary.WriteLine(TraceLevel.Info, table.Name + ": " + retVal.ToString()); //var indices = db.GetDialectProvider().ToCreateIndexStatements(table.GetType()); //foreach (var item in indices) // item.PrintDump(); //var createTableSql = OrmLiteConfig.DialectProvider.ToCreateTableStatement(table.GetType()); //TraceLibrary.WriteLine(TraceLevel.Info, createTableSql); } SQLiteConnection sql = db.ToDbConnection() as SQLiteConnection; Assert.IsNotNull(sql); string filename = Path.GetFullPath(@"D:\Desktop\FromMemoryDb.sqlite"); using (SQLiteConnection db2 = new SQLiteConnection(string.Format("data source={0};Version=3;New=True", filename))) { db2.Open(); sql.BackupDatabase(db2, "main", "main", -1, null, 0); db2.Close(); } } }
private void Backup() { try { using (var src = new SQLiteConnection(SrcZip)) using (var dst = new SQLiteConnection(DstZip)) using (DisposeWatch.Start(e => Console.WriteLine($"Backup Completed in {e.TotalMilliseconds} ms"))) { src.Open(); dst.Open(); Console.WriteLine("Start Copy"); src.BackupDatabase(dst, "main", "main", -1, null, 0); Console.WriteLine("End Copy"); } } catch (Exception ex) { Console.WriteLine(); Console.WriteLine(); Console.WriteLine(); Console.WriteLine("Couldn't copy"); Console.WriteLine(ex.Message); } }
// Loads Database from Hardrive into memory private static SQLiteConnection Connect() { if (InMemoryDatabase == null || InMemoryDatabase.State != System.Data.ConnectionState.Open || !Loaded) { // Release database in memory if it has been invalided with Loaded if (!Loaded && (InMemoryDatabase != null)) { InMemoryDatabase.Dispose(); } // Start Open off new Database file InMemoryDatabase = new SQLiteConnection("Data Source=:memory:"); InMemoryDatabase.Open(); // Load the database SQLiteConnectionStringBuilder conn = new SQLiteConnectionStringBuilder(); conn.DataSource = DatabasePath; conn.Version = 3; using (var fileDB = new SQLiteConnection(conn.ConnectionString, true)) { fileDB.Open(); fileDB.BackupDatabase(InMemoryDatabase, "main", "main", -1, null, 0); Modified = false; Loaded = true; } } return(InMemoryDatabase); }
public static void Backup(string sourceConnectionString, string appDataDirectory) { var now = DateTime.UtcNow; var backupDirectory = Path.Combine(appDataDirectory, "Backup"); if (!Directory.Exists(backupDirectory)) { Directory.CreateDirectory(backupDirectory); } if (HasBackupForToday(now, backupDirectory)) { return; } var backupFile = "{0}.sqlite".F(now.ToString("yyyy-MM-dd_hh-mm-ss")); backupFile = Path.Combine(backupDirectory, backupFile); Logger.I("Database backup to {0}", backupFile); string backupConnectionString = "data source={0}".F(backupFile); using (var backupConnection = new SQLiteConnection(backupConnectionString)) using (var sourceConnection = new SQLiteConnection(sourceConnectionString)) { backupConnection.Open(); sourceConnection.Open(); sourceConnection.BackupDatabase(backupConnection, "main", "main", -1, null, 0); } DeleteOldBackups(backupDirectory, 5); }
private DbConnectionCreator() { if (Logger == null) { Logger = LogManager.GetLogger("SQLite"); } var db = $"Data Source={ClientLocalDb.FileDatabase};Version=3;"; if (InMemory()) { _internalConnection = new SQLiteConnection(db); _internalConnection.Open(); Connection = new SQLiteConnection("Data Source=:memory:;Version=3;"); Connection.Open(); Logger.Info("Загрузка базы в память..."); _internalConnection.BackupDatabase(Connection, "main", "main", -1, null, -1); Logger.Info("Загрузка базы в память завершена."); } else { Logger.Info("Подключение к файлу бд..."); _internalConnection = new SQLiteConnection(db); _internalConnection.Open(); Connection = _internalConnection; } }
public bool Backup(string filename) { if (!IsOpen()) { return(false); } Flush(false); //Flushign any pending changes but do not create a new transaction. using (SQLiteConnection conn = new SQLiteConnection(SqliteLibrary.GetConnectionString(filename))) { try { SQLiteConnection db = DbConnection.ToDbConnection() as SQLiteConnection; conn.Open(); db.BackupDatabase(conn, "main", "main", -1, null, 0); } finally { conn.Close(); } } //A backup to an in-memory database returns false if (filename == ":memory:") { return(false); } return(File.Exists(filename)); }
public void Init() { if (_zipPath != null) { using (ZipArchive archive = ZipFile.Open(_zipPath, ZipArchiveMode.Update)) { ZipArchiveEntry entry = archive.GetEntry(_DBPathInsideZip); _DBName = entry.Name; _DBPathInDisk = $"C:\\{_DBName}"; var stream = entry.Open(); using (_fileStream = File.Create(_DBPathInDisk)) { stream.Seek(0, SeekOrigin.Begin); stream.CopyTo(_fileStream); } stream.Close(); } } _memoryConnection = new SQLiteConnection("Data Source=:memory:"); _connection = new SQLiteConnection($"Data Source={_DBPathInDisk};"); _memoryConnection.Open(); _connection.Open(); _connection.BackupDatabase(_memoryConnection, "main", "main", -1, null, 0); _connection.Close(); //_cmd = new SQLiteCommand(_connection); _cmd = new SQLiteCommand(_memoryConnection); }
public override void Initialize(String conString) { if (InMemory) { try { SQLiteConnection sourceConnection = new SQLiteConnection(conString); SQLiteConnection destinationConnection = new SQLiteConnection("Data Source=:memory:"); sourceConnection.Open(); destinationConnection.Open(); sourceConnection.BackupDatabase(destinationConnection, "main", "main", -1, Callback, 0); sourceConnection.Close(); destinationConnection.Close(); Connection = destinationConnection; } catch (Exception e) { Console.WriteLine(e.StackTrace); } } else { Connection = new SQLiteConnection(conString); } }
private void button6_Click_1(object sender, EventArgs e) { this.Enabled = false; DateTime currentDate = DateTime.Now; string destFolder = Sqlite.GetFolderPath(); if (destFolder == "") { MessageBox.Show("Please select any folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } string destPath = string.Format("{0}/backup-{1}.db", destFolder, currentDate.ToString("dd-MM-yyyy")); if (File.Exists(destPath)) { destPath = string.Format("{0}/backup-{1}.db", destFolder, currentDate.ToString("dd-MM-yyyy-fff")); } using (var source = new SQLiteConnection("Data Source=main.db")) using (var destination = new SQLiteConnection(string.Format(@"Data Source={0}", destPath))) { source.Open(); destination.Open(); source.BackupDatabase(destination, "main", "main", -1, null, 0); } this.Enabled = true; }
public void Backup(string backupFilename) { if (databasefile == backupFilename) { Console.WriteLine(string.Format("Cannot overwrite current running database. Chose another destination.")); return; } if (File.Exists(backupFilename)) { Console.WriteLine(string.Format("File {0} exists. Overwriting file.", backupFilename)); } StringBuilder b = new StringBuilder(); DbConnectionStringBuilder.AppendKeyValuePair(b, "Data Source", backupFilename); DbConnectionStringBuilder.AppendKeyValuePair(b, "Version", "3"); DbConnectionStringBuilder.AppendKeyValuePair(b, "New", "True"); DbConnectionStringBuilder.AppendKeyValuePair(b, "Compress", "True"); DbConnectionStringBuilder.AppendKeyValuePair(b, "Journal Mode", "Off"); SQLiteConnection sqliteBckConn = new SQLiteConnection(b.ToString()); sqliteBckConn.Open(); sqliteConn.BackupDatabase(sqliteBckConn, sqliteBckConn.Database, sqliteConn.Database, -1, null, 10); // shrink database vacuum(sqliteBckConn); sqliteBckConn.Close(); sqliteBckConn.Dispose(); }
public DBConnectionCreator() { if (_logger == null) { _logger = LogManager.GetLogger("ClientServer"); } var db = $"Data Source={FileDatabase};Version=3;"; if (InMemory()) { SQLiteConnection tmpConnection = new SQLiteConnection(db); tmpConnection.Open(); Connection = new SQLiteConnection("Data Source=:memory:;Version=3;"); Connection.Open(); _logger.Info("Загрузка базы в память..."); tmpConnection.BackupDatabase(Connection, "main", "main", -1, null, -1); tmpConnection.Close(); _logger.Info("Загрузка базы в память завершена."); } else { _logger.Info("Подключение к файлу бд..."); Connection = new SQLiteConnection(db); Connection.Open(); } }
private void savaDB_Button_Click(object sender, EventArgs e) { SaveFileDialog dialog = new SaveFileDialog(); dialog.FileName = dbFileName; try { if (dialog.ShowDialog() == DialogResult.OK) { //string pathNewDB = @"C:\Users\Алексей\Downloads\SaveDBHere"; string pathNewDB = Path.GetDirectoryName(dialog.FileName); using (var location = new SQLiteConnection(ConnString)) using (var destination = new SQLiteConnection(string.Format(@"Data Source={0}\RentDB; Version=3;", pathNewDB))) { location.Open(); destination.Open(); location.BackupDatabase(destination, "main", "main", -1, null, 0); location.Close(); destination.Close(); } MessageBox.Show("Резервная копия базы данных успешно создана.", "Уведомление", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Saves the SQLite DB to a local file. /// </summary> /// <param name="sender">Unused</param> /// <param name="e">Unused</param> public override void RunDbBackup(object sender, ElapsedEventArgs e) { string backupFileName = Path.Combine(databaseFolder, DateTime.UtcNow.ToString("yyy-MM-dd-hh-mm") + ".backup"); logger.Info("Backing up the DB to " + backupFileName); Stopwatch backupTimer = Stopwatch.StartNew(); try { SQLiteConnection.CreateFile(backupFileName); using (SQLiteConnection backupConnection = new SQLiteConnection($"Data Source={backupFileName}")) { backupConnection.Open(); database.BackupDatabase(backupConnection, "main", "main", -1, null, 1000); } logger.Info("Backup completed successfully in " + backupTimer.ElapsedMilliseconds + " ms."); } catch (Exception ex) { logger.Error("Error saving the DB backup: " + ex.Message + ". " + ex.StackTrace); } backupTimer.Stop(); }
private void BackupDatabase(Database srcDatabase, string dstFileName) { var destination = Database.GetOrCreate(dstFileName); using (SQLiteConnection srcConnection = ConnectionFactory.CreateSQLiteConnection(srcDatabase)) { srcConnection.Open(); using (SQLiteConnection dstConnection = ConnectionFactory.CreateSQLiteConnection(destination, false)) { dstConnection.Open(); srcConnection.BackupDatabase( dstConnection, "main", "main", -1, null, -1 ); } } GC.Collect(); }
/// <summary>备份数据库 /// </summary> /// <param name="isFileToMemory">是否是文件数据库备份到内存数据库; /// isFileToMemory为true指的是从文件数据库导入到当前内存数据库; /// isFileToMemory为false指的是从当前内存数据库导出到文件数据库。 /// </param> private void BackupDatabase(bool isFileToMemory) { using (SQLiteConnection dbfileConnection = GetCon(false)) { memoryConn = GetCon(true); //如果连接是关闭状态就打开 if (dbfileConnection.State == ConnectionState.Closed) { dbfileConnection.Open(); } if (memoryConn.State == ConnectionState.Closed) { memoryConn.Open(); } if (isFileToMemory) { dbfileConnection.BackupDatabase(memoryConn, "main", "main", -1, null, 0); //memoryConn = dbmemConnection; useInMemory = true; } else { memoryConn.BackupDatabase(dbfileConnection, "main", "main", -1, null, 0); } } }
public void Execute(string sourceConnectionString, string destinationConnectionString, int pagesToBackupInEachStep) { try { using (var srcConnection = new SQLiteConnection(sourceConnectionString)) using (var destConnection = new SQLiteConnection(destinationConnectionString)) { srcConnection.Open(); destConnection.Open(); // Need to use the "main" names as specified at http://www.sqlite.org/c3ref/backup_finish.html#sqlite3backupinit srcConnection.BackupDatabase(destConnection, "main", "main", pagesToBackupInEachStep, Callback, 10); destConnection.Close(); srcConnection.Close(); } } catch (Exception ex) { foreach (var observer in _observers) { observer.OnError(ex); } } foreach (var observer in _observers) { observer.OnCompleted(); } }
public static void CreateBackUpDb() { if (!Directory.Exists(globalParameters.dbDirPath)) { Directory.CreateDirectory(globalParameters.dbDirPath); // File.SetAttributes(dirPath, FileAttributes.Hidden); } if (File.Exists(globalParameters.tempDb)) { File.Delete(globalParameters.tempDb); } using (SQLiteConnection conn = new SQLiteConnection(globalParameters.dbPath)) { conn.Open(); using (SQLiteConnection backupConn = new SQLiteConnection(globalParameters.backupDbPath)) { backupConn.Open(); conn.BackupDatabase(backupConn, "main", "main", -1, null, 0); conn.Close(); backupConn.Close(); } } string change = globalParameters.dbPath; globalParameters.dbPath = globalParameters.backupDbPath; globalParameters.backupDbPath = change; }
public void Load(string fileName) { SQLiteConnection source = new SQLiteConnection(string.Format("Data Source='{0}';Version=3", fileName)); source.Open(); source.BackupDatabase(connection, "main", "main", -1, null, -1); source.Close(); }
public void Save(string fileName) { SQLiteConnection dest = new SQLiteConnection(string.Format("Data Source='{0}';Version=3", fileName)); dest.Open(); connection.BackupDatabase(dest, "main", "main", -1, null, 0); dest.Close(); }
// TODO: Extract to ZenForge internal bool CookDB(string cookPath) { var fileConnection = new SQLiteConnection($"Data Source = {cookPath + DatabaseName + DatabaseFileExtension}; Version = 3;"); fileConnection.Open(); _registryConnection.BackupDatabase(fileConnection, _registryConnection.Database, _registryConnection.Database, -1, null, -1); return(true); }
public void SaveToDisk() { string FileName = Properties.Settings.Default.PATH + Properties.Settings.Default.Indexer; var output = new SQLiteConnection("Data Source=" + FileName + "; Version=3; UTF8Encoding=True;"); output.Open(); connection.BackupDatabase(output, "main", "main", -1, null, -1); }
private void CloseConnection() { source.Open(); // save memory db to file sql_con.BackupDatabase(source, "main", "main", -1, null, 0); source.Close(); }
protected void loadDBFromFile() { if (this.keepInMemory) { SQLiteConnection filePersists = this.openCreateFileDB(); filePersists.BackupDatabase(this.connection, "main", "main", -1, null, 0); filePersists.Close(); } }
//CreateParams backup of db internal static void BackupDB() { originalDatabase = new SQLiteConnection(SQLiteConnectionString); backupDatabase = new SQLiteConnection(backupDB); originalDatabase.Open(); backupDatabase.Open(); originalDatabase.BackupDatabase(backupDatabase, "main", "main", -1, null, -1); originalDatabase.Close(); backupDatabase.Close(); }
public void BackUpDatabase() { using (SQLiteConnection disk = new SQLiteConnection(m_csb.ConnectionString)) using (SQLiteConnection memory = new SQLiteConnection("Data Source=:memory:")) { disk.Open(); disk.Execute(@"create table Test (Id integer primary key, String text); insert into Test(Id, String) values(1, 'one'), (2, 'two'), (3, 'three');"); memory.Open(); disk.BackupDatabase(memory, "main", "main", -1, null, 0); using (var reader = memory.ExecuteReader("select Id from Test where length(String) = @len", new { len = 3 })) { var results = reader.ReadAll<long>().ToList(); Assert.That(results, Is.EqualTo(new long[] { 1, 2 })); } } }