Click here to Skip to main content
13,189,884 members (60,817 online)
Click here to Skip to main content
Add your own
alternative version

Stats

394.3K views
28.4K downloads
330 bookmarked
Posted 14 Aug 2012

MySqlBackup.NET - MySQL Backup Solution for C#, VB.NET, ASP.NET

, 8 Aug 2015
Rate this:
Please Sign up or sign in to vote.
A tool to export and import MySQL database in .NET

Available at:

Contents

  1. Introduction
  2. Features & Dependencies
  3. Background
  4. Basic Usage
  5. Example of Using in ASP.NET
  6. More Guides And Examples
  7. History

1. Introduction

This article introduce a tool (DLL) that can backup/restore MySQL database in C# or VB.NET and some sample codes on how to use it. It is an alternative to MySqlDump.

Another benefits of making this tool is, we don't have to rely on two small programs - MySqlDump.exe and MySql.exe to perform the backup and restore task. We will have better control on the output result.

The most common way to backup a MySQL Database is by using MySqlDump.exe and MySQL Workbench.

MySQL Workbench is good for developers, but, when comes to client or end-user, the recommended way is to get every parameter preset and all they need to know is press the big button "Backup" and everything is done. Using MySQL Workbench as a backup tool is not a suitable solution for client or end-user.

On the other hand, MySqlDump.exe cannot be used for Web applications. As most web hosting providers forbid that, MySqlBackup.NET will be helpful in building a web-based (ASP.NET/Web-Services) backup tool.


2. Features & Dependencies

Features

  • Backup and Restore of MySQL Database
  • Can be used in any .NET Languages.
  • Export/Import to/from MemoryStream
  • Conditional Rows Export (Filter Tables or Rows)
  • Build-In Internal Encryption Function
  • Able Restore to New Non-Existed Database
  • Progress Report is Available for Both Export and Import Task.
  • Able to export rows into different mode. (Insert, Insert Ignore, Replace, On Duplicate Key Update, Update)
  • Can be used directly in ASP.NET or web services.

Prerequisite / Dependencies

MySqlBackup.NET is built on top of MySQL dot net Connector/Net (MySql.Data.DLL)

  • A reference of this DLL must be added into your project in order for MySqlBackup.NET to work.
  • MySql.Data.DLL is developed by Oracle Corporation, licensed under GPL License (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html).

3. Background

This article is assumed that you have already familiar with MySQL dot net connector (MySql.Data.dll) with minimum knowledge that you are able to perform the four basic operation SELECT, INSERT, UPDATE and <code>DELETE. In case you are not, you can read the walk-through and explanation on Connecting C# to MySQL at: [http://www.codeproject.com/Articles/43438/Connect-C-to-MySQL]


4. Basic Usage

Add this using statement before coding with MySqlBackup.NET:

using MySql.Data.MySqlClient; 

Simple Export Example

string constring = "server=localhost;user=root;pwd=qwerty;database=test;";
string file = "C:\\backup.sql";
using (MySqlConnection conn = new MySqlConnection(constring))
{
    using (MySqlCommand cmd = new MySqlCommand())
    {
        using (MySqlBackup mb = new MySqlBackup(cmd))
        {
            cmd.Connection = conn;
            conn.Open();
            mb.ExportToFile(file);
            conn.Close();
        }
    }
}

Simple Import Example

string constring = "server=localhost;user=root;pwd=qwerty;database=test;";
string file = "C:\\backup.sql";
using (MySqlConnection conn = new MySqlConnection(constring))
{
    using (MySqlCommand cmd = new MySqlCommand())
    {
        using (MySqlBackup mb = new MySqlBackup(cmd))
        {
            cmd.Connection = conn;
            conn.Open();
            mb.ImportFromFile(file);
            conn.Close();
        }
    }
}

Above examples will export and import a MySQL database with default options. There are some options that can modify the export and import behavior. These options are defined in:

  • MySqlBackup.ExportInfo
  • MySqlBackup.ImportInfo

Example of customize export behavior:

  • Create new database
  • Only export table's structures
  • Don't export rows of data

Sample Codes:

string constring = "server=localhost;user=root;pwd=1234;database=test1;";
string file = "Y:\\backup.sql";
using (MySqlConnection conn = new MySqlConnection(constring))
{
    using (MySqlCommand cmd = new MySqlCommand())
    {
        using (MySqlBackup mb = new MySqlBackup(cmd))
        {
            cmd.Connection = conn;
            conn.Open();
            mb.ExportInfo.AddCreateDatabase = true;
            mb.ExportInfo.ExportTableStructure = true;
            mb.ExportInfo.ExportRows = false;
            mb.ExportToFile(file);
        }
    }
}

Example of customize import behavior:

  • Import to new (non-exist) database
  • Set default character of new database to utf8

Sample Codes:

string constring = "server=localhost;user=root;pwd=1234;database=test1;";
string file = "Y:\\backup.sql";
using (MySqlConnection conn = new MySqlConnection(constring))
{
    using (MySqlCommand cmd = new MySqlCommand())
    {
        using (MySqlBackup mb = new MySqlBackup(cmd))
        {
            cmd.Connection = conn;
            conn.Open();
            mb.ImportInfo.TargetDatabase = "test2";
            mb.ImportInfo.DatabaseDefaultCharSet = "utf8";
            mb.ImportFromFile(file);
        }
    }
}

Full List of ExportInfo Options

OptionsData TypeDefault ValueDescriptions
TablesToBeExportedListList<string>EmptyOnly defined tables in the List will be exported.
TablesToBeExportedDicDictionary <string,string>EmptyOnly defined tables in the Dictionary will be exported. Key refers to table's name, Value will be SELECT statement. The SELECT statement is used to filter rows. Conditioning rows export. Example: SELECT * FROM tableA WHERE membershipid = 1
RecordDumpTimebooltrueGets or Sets a value indicates whether the Dump Time should recorded in dump file.
EnableEncryptionboolfalseGets or Sets a value indicates whether the Exported Dump File should be encrypted.
EncryptionPasswordstringEmptySets the password used to encrypt the exported dump file.
AddCreateDatabaseboolfalseGets or Sets a value indicates whether the SQL statement of "CREATE DATABASE" should added into dump file.
ExportTableStructurebooltrueGets or Sets a value indicates whether the Table Structure (CREATE TABLE) should be exported.
ResetAutoIncrementbooltrueGets or Sets a value indicates whether the value of auto-increment of each table should be reset to 1.
ExportRowsbooltrueGets or Sets a value indicates whether the Rows should be exported.
MaxSqlLengthint5x1024x1024 = 5MBGets or Sets the maximum length for combining multiple INSERTs into single sql.
ExportProceduresbooltrueGets or Sets a value indicates whether the Stored Procedures should be exported.
ExportFunctionsbooltrueGets or Sets a value indicates whether the Stored Functions should be exported.
ExportTriggersbooltrueGets or Sets a value indicates whether the Stored Triggers should be exported.
ExportViewsbooltrueGets or Sets a value indicates whether the Stored Views should be exported.
ExportEventsbooltrueGets or Sets a value indicates whether the Stored Events should be exported.
IntervalForProgressReportint50Gets or Sets a value indicates the interval of time (in miliseconds) to raise the event of ExportProgressChanged.
GetTotalRowsBeforeExportbooltrue (modified in v2.0.9)Gets or Sets a value indicates whether the totals of rows should be counted before export process commence.
ScriptsDelimiterstring|Gets or Sets the delimiter used for exporting Procedures, Functions, Events and Triggers.
ExportRoutinesWithoutDefinerbooltrueGets or Sets a value indicates whether the exported Scripts (Procedure, Functions, Events, Triggers, Events) should include DEFINER.
ExcludeTables
(v2.0.5)
List<string>EmptyGets or Sets the tables (black list) that will be excluded for export. The rows of the these tables will not be exported too.
GetDocumentHeaders(MySqlCommand)
(v2.0.5)
List<string>see demo appGets the list of document headers.
SetDocumentHeaders(List<string>)
(v2.0.5)
List<string>see demo app_Sets the document headers.
GetDocumentFooters()
(v2.0.5)
List<string>see demo appGets the document footers.
SetDocumentFooters(List<string>)
(v2.0.5)
List<string>see demo appSets the document footers.
RowsExportMode
(v2.0.7)
EnumInsertGets or Sets a enum value indicates how the rows of each table should be exported.
INSERT = The default option. Recommended if exporting to new or empty database. If the primary key is existed, the process will halt;
INSERT IGNORE = If the primary key existed, skip it; Useful in finding missing rows.
REPLACE = If the primary key existed, delete the row and insert new data;
OnDuplicateKeyUpdate = If the primary key existed, update the row;
UPDATE = If the primary key is not existed, skip it, else update it.
WrapWithinTransaction
(v2.0.7)
boolfalseGets or Sets a value indicates whether the rows dump should be wrapped with transaction. Recommended to set this value to FALSE if using RowsExportMode = "INSERT" or "INSERTIGNORE" or "REPLACE", else TRUE.

Full List of ImportInfo Options

OptionsData TypeDefault ValueDescriptions
EnableEncryptionboolfalseGets or Sets a value indicates whether the Imported Dump File is encrypted.
EncryptionPasswordstringEmptySets the password used to decrypt the exported dump file.
IntervalForProgressReportint100Gets or Sets a value indicates the interval of time (in miliseconds) to raise the event of ExportProgressChanged.
TargetDatabasestringEmptyGets or Sets the name of target database. If the database is not existed, it will be created.
DatabaseDefaultCharSetstringEmptyGets or Sets the default character set of the target database. Will only take effect if importing to new non-existed database.
IgnoreSqlErrorboolfalseGets or Sets a value indicates whether SQL errors occurs in import process should be ignored.
ErrorLogFilestringEmptyGets or Sets the file path used to log error messages.

 

 


5. Example of Using in ASP.NET

Sample code for Export. Below codes will export the content into MemoryStream, then transmit it directly for download.

using System.IO;

string connstr = "server=localhost;user=root;pwd=1234;database=test;";
MemoryStream ms = new MemoryStream();
using (MySqlConnection conn = new MySqlConnection(connstr))
{
    MySqlCommand cmd = new MySqlCommand();
    MySqlBackup mb = new MySqlBackup(cmd);
    cmd.Connection = conn;
    conn.Open();
    mb.ExportToMemoryStream(ms);
}
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment; filename=backup.sql");
Response.BinaryWrite(ms.ToArray());
Response.End();

Sample code for Upload and Import:

string connstr = "server=localhost;user=root;pwd=1234;database=test;";
byte[] ba = FileUpload1.FileBytes;
MemoryStream ms = new MemoryStream(ba);
using (MySqlConnection conn = new MySqlConnection(connstr))
{
    MySqlCommand cmd = new MySqlCommand();
    MySqlBackup mb = new MySqlBackup(cmd);
    cmd.Connection = conn;
    conn.Open();
    mb.ExportToMemoryStream(ms);
}
Header.Controls.Add(new LiteralControl("<script type=\"text/javascript\">alert('ok');</script>"));

6. More Guides And Examples

More guides and examples available at the project site's documentation:
https://github.com/adriancs2/MySqlBackup.Net/wiki[^]

Below are some of the guides


7. History

  • 08 August 2015 - Release of V2.0.9.2
  • 19 July 2015 - Release of V2.0.9
  • 25 Feb 2015 - Release of V2.0.8
  • 26 Jan 2015 - Release of V2.0.7.1
  • 25 Jan 2015 - Release of V2.0.7
  • 17 Nov 2014 - Release of V2.0.6
  • 20 Oct 2014 - Release of V2.0.5
  • ... lots of changes ...
  • 19 Sep 2011 - Version 1.0 - Initial release

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication

Share

About the Author

adriancs
Software Developer
Malaysia Malaysia
Programming is an art.

You may also be interested in...

Comments and Discussions

 
QuestionOption for 1 Insert by line? Pin
Alexandre Marcus dos Santos31-Aug-17 9:28
memberAlexandre Marcus dos Santos31-Aug-17 9:28 
AnswerRe: Option for 1 Insert by line? Pin
adriancs11-Sep-17 18:04
professionaladriancs11-Sep-17 18:04 
QuestionWhy version 2.0 has less features than version 1.5? Pin
Clivic TR24-Mar-17 22:01
memberClivic TR24-Mar-17 22:01 
AnswerRe: Why version 2.0 has less features than version 1.5? Pin
adriancs1-Apr-17 4:50
professionaladriancs1-Apr-17 4:50 
GeneralRe: Why version 2.0 has less features than version 1.5? Pin
Clivic TR8-Apr-17 3:24
memberClivic TR8-Apr-17 3:24 
QuestionError the system Can't Find the Reference Specified Pin
Samoual Shingrai5-Jul-16 6:12
memberSamoual Shingrai5-Jul-16 6:12 
AnswerRe: Error the system Can't Find the Reference Specified Pin
adriancs6-Jul-16 1:07
professionaladriancs6-Jul-16 1:07 
QuestionExport Sizes Differ Pin
Member 1232267511-Feb-16 23:10
memberMember 1232267511-Feb-16 23:10 
AnswerRe: Export Sizes Differ Pin
adriancs23-Feb-16 22:07
professionaladriancs23-Feb-16 22:07 
QuestionVB.NET error Pin
GirorgioC20-Jan-16 5:26
memberGirorgioC20-Jan-16 5:26 
AnswerRe: VB.NET error Pin
Member 951947518-Feb-16 0:42
memberMember 951947518-Feb-16 0:42 
QuestionBackup lost Unicode data and can not Restore the binary data Pin
Nguyen Van Bay5-Jan-16 23:04
memberNguyen Van Bay5-Jan-16 23:04 
AnswerRe: Backup lost Unicode data and can not Restore the binary data Pin
adriancs6-Jan-16 14:41
professionaladriancs6-Jan-16 14:41 
GeneralRe: Backup lost Unicode data and can not Restore the binary data Pin
Nguyen Van Bay6-Jan-16 17:36
memberNguyen Van Bay6-Jan-16 17:36 
GeneralRe: Backup lost Unicode data and can not Restore the binary data Pin
adriancs6-Jan-16 21:06
professionaladriancs6-Jan-16 21:06 
GeneralRe: Backup lost Unicode data and can not Restore the binary data Pin
Nguyen Van Bay7-Jan-16 0:35
memberNguyen Van Bay7-Jan-16 0:35 
GeneralRe: Backup lost Unicode data and can not Restore the binary data Pin
Nguyen Van Bay7-Jan-16 14:50
memberNguyen Van Bay7-Jan-16 14:50 
GeneralnRe: Backup lost Unicode data and can not Restore the binary data Pin
adriancs8-Jan-16 22:13
professionaladriancs8-Jan-16 22:13 
GeneralRe: nRe: Backup lost Unicode data and can not Restore the binary data Pin
Nguyen Van Bay10-Jan-16 19:01
memberNguyen Van Bay10-Jan-16 19:01 
GeneralRe: nRe: Backup lost Unicode data and can not Restore the binary data Pin
adriancs11-Jan-16 20:35
professionaladriancs11-Jan-16 20:35 
GeneralRe: nRe: Backup lost Unicode data and can not Restore the binary data Pin
nvbay23-Jan-17 23:47
membernvbay23-Jan-17 23:47 
QuestionNot converting ASCII NULL to ESC SEQ \0 Pin
eZov30-Oct-15 1:54
membereZov30-Oct-15 1:54 
AnswerRe: Not converting ASCII NULL to ESC SEQ \0 Pin
adriancs13-Dec-15 1:51
mvpadriancs13-Dec-15 1:51 
QuestionImport Does not work Pin
mailparikshit@yahoo.com26-Oct-15 19:29
membermailparikshit@yahoo.com26-Oct-15 19:29 
AnswerRe: Import Does not work Pin
adriancs26-Oct-15 20:42
mvpadriancs26-Oct-15 20:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171016.2 | Last Updated 8 Aug 2015
Article Copyright 2012 by adriancs
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid