Click here to Skip to main content
Click here to Skip to main content

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

By , 14 Dec 2012
 

Available at: 

Contents    

  1. Introduction  
  2. Features, Limitation & Dependencies 
  3. Change Log 
  4. Background  
  5. MySqlBackup.NET 1.5 Class Structure 
  6. Adding MySqlBackup.NET Into Your Project
  7. Basic Examples
  8. Examples of Using MySqlBackup.NET in ASP.NET 
  9. About Synchronous And Asynchronous Mode
  10. Using MySqlBackup.NET with Progress Bar 
  11. Gathering Information After Export/Import Process Completed
  12. About Importing (Restoring) to Another/New Database
  13. MySqlBackup.dll V1.1
  14. Frequently Asked Questions (FAQ)
  15. Development of the project. 
  16. History
 

1. Introduction 

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

On the other hand, this tool uses native .NET language to handle all values and parameters, therefore it can handle Unicode/UTF8 character (multi-language) well.

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.

This tool is develop in C# but useable in VB.NET.

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

MySQL Administrator 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 Administrator as a backup tool is not a suitable solution for client or end-user.

On the other hand, MySqlDump is another tool that can customize within code to meet specific situation. However, MySqlDump has compatible problems while handling with Unicode characters, for example Korean, Japanese, Chinese and Russian characters. The data will corrupt during the encoding between MySQL database and MySqlDump. Besides, MySqlDump cannot be used for Web applications. As most providers forbid that, MySqlBackup.NET will be helpful in building a web-based (ASP.NET) backup tool.   


2. Features, Limitation & Dependencies 

Features

  • Export/Import Table's Structures & Rows
  • Export/Import Stored Procedures, Functions, Triggers, Events, Views
  • Custom Tables and Rows Export.
  • Able to apply encryption to the process.
  • Export BLOB and save as files. 
  • Gather SQL Syntax errors during Import process.
  • Export/Import will report progress. Enable the usage of progress bar. 
  • Able to execute in Synchronous or Asynchronous mode.
  • Export/Import To/From Zip File.

Limitation

Cannot handle multiple MEDIUMTEXT and MEDIUMBLOB data type. (some where more than 18MB length in single SQL query)

Multiple MEDIUMTEXT and MEDIUMBLOB will make (a single SQL) System.String and MySqlCommand.CommandText long enough to cause System.OutOfMemoryException.

This is not limited by the number of rows. MySqlBackup.NET can backup & restore millions of rows.

However, one thing for sure is, if the length of SQL can be inserted into MySQL database by any .NET application, MySqlBackup.NET is able to do so. Conversely, if you can't insert the SQL (because of the length) by any .NET apps, MySqlBackup.NET too can't.

If the user used in the MySql Connection has super privilege, then MySqlBackup.NET will set the max_allowed_packet to 1GB, which is the maximum length of single query of MySQL. 

MySqlBackup.NET is currently not able to backup & restore LONGBLOB and LONGTEXT data type.

It is somehow wondering that:

The computer has 4GB of RAM and there are still 2.5GB free, why the software still raise the exception telling that it is Out Of Memory?  

After some findings, 1 of the useful information may describe the problem:

Maybe there are some techniques out there that can tweaks the memory handling which allow a System.String able to hold a length of data up to 1GB. 

Or maybe, there is another method to replace this. However, this is still under investigation.  

Dependencies

MySqlBackup.NET is built on top the following tools/technologies:

  • MySQL dot net Connector/Net (http://www.mysql.com) 
    • A reference of this DLL must be added into your project in order for MySqlBackup.NET to work.
    • Released Precompiled MySqlBackup.DLL requires Connector/Net Version 6.6.4 (MySql.Data.DLL). MySql.Data.DLL is developed by Oracle Corporation  and is licensed under GPL License (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html).
  • DotNetZip (http://dotnetzip.codeplex.com/)
    • This class library enables MySqlBackup.NET compress the Exported SQL Dump File into Zip file.
    • It also enables MySqlBackup.NET extract the dump file from a zip file.
    • DotNetZip is licensed under Microsoft Public License. 


3. Change Log    

V1.5.7 (25 Jan 2013) 

  • Fix Bug: An error will occur when ExportInfo.AsynchronousMode = true and ExportIfo.CalculateTotalRowsFromDatabase = false are set at the same time.

V1.5.6 (14 Dec 2012)

  • Fix Bug: If encryption is applied in Export Process, the generated encrypted SQL file is not able to import Stored Procedures, Functions, Triggers, Events and View.
    > Discussion: MySqlBackup.dll
  • Fix Bug: In some unknown cases, the SHOW CREATE TABLE `tablename` query will return byte array.
    > http://www.codeproject.com/Messages/4450086/Small-changes-in-Code.aspx
  • Improve 1: During Export, StreamWriter is opened and closed several times when writting to the dump file, which this is considered as not a good practice.
  • Improve 2: SQL line in class Database method GetEvents: "SHOW EVENTS WHERE Db LIKE '" + DatabaseName + "';" might potentially cause errors due to case sensitivity.
  • New Feature: MySqlBackup.NET is able to export as compressed zip file which results approximately 10 times smaller(file size) than original exported dump file.
    New option: ExportInfo.ZipOutputFile.
  • MySqlBackup.NET can import a compressed SQL dump file in zip format.

V1.5.5 (11 Dec 2012)

[Full Change Log


4. 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 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

 


5. MySqlBackup.NET Class Structure 1.5.6 beta (14 December 2012) 

Constructor

  • MySqlBackup()
  • MySqlBackup(string)
  • MySqlBackup(MySqlConnection)
  • MySqlBackup(MySqlCommand)

Public Properties

  • Connection - MySqlConnection - Gets or Sets the MySqlConnection that used by this instance.
  • DatabaseInfo - Database - Gets the infomations about the connected database.
    • Properties, Fields, Methods
      • CreateDatabaseSql - string - Gets the SQL Statement of CREATE DATABASE of this database.
      • DatabaseName - string - Gets the Name of this Database.
      • Tables - Dictionary<string, Table> - Gets all the Tables' information. Key = Table name; Value = Table.
      • ServerVersion - string - Gets the MySQL Server Version's number and name.
      • ServerVersionNo - string- Gets the MySQL Server Version's number.
      • ServerMajorVersion - double - Gets the MSQL Server Major Version's number.
      • DefaultDatabaseCharSet - string - Gets the default character set of current database.
      • TableNames - string[] - Gets all table's name.
      • StoredProcedure - Dictionary<string,string> - Gets or Sets Stored Procedures of current database.
      • StoredFunction - Dictionary<string,string> - Gets or Sets Stored Functions of current database.
      • StoredTrigger - Dictionary<string,string> - Gets or Sets Stored Triggers of current database;
      • StoredEvents - Dictionary<string,string> - Gets or Sets Stored Events of current database.
      • StoredView - Dictionary<string,string> - Gets or Sets Stored Views of current database.
      • GetTotalRows - Long - Gets the total rows in all tables of current database.
      • CalculateTotalRowsProgressChanged - Event - Occur when total rows calculation of 1 table has completed.
      • CalculateTotalRowsCompleted - Event - Occur when total rows calculation of all table has completed.
  • ExportInfo (ExportInformations) - Gets or Sets the Informations that define behaviour of Export Process. Read more at Class of ExportInformations below.
    • Properties, Methods and Fields
      • FileName -string - Gets or Sets the full path and file name (dump file) that will be saved to. The output of the export process.
      • TableCustomSql - Dictionary<string,string> - Gets or Sets the tables that will be exported and the SQL for selecting the rows of the tables. If the SQL is left blank, the SQL will replace by "SELECT * FROM tablename". Key = tablename, Value = SQL
      • TablesToBeExported - string[] - Gets or Sets the tables that will be exported
      • RecordDumpTime - bool - Gets or Sets a value indicates whether the Dump Time should recorded in dump file.
      • AsynchronousMode - bool - Gets or Sets a value indicates whether the Export process should run in Asynchronous Mode.
      • CalculateTotalRowsFromDatabase - bool - Gets or Sets a value indicates whether total rows should be calculated before Export Process starts.
      • AutoCloseConnection - bool - Gets or Sets a value indicates whether the MySqlConnection and MySqlCommand used should close and dispose after export process finished.
      • EnableEncryption - bool - Gets or Sets a value indicates whether the Exported Dump File should be encrypted.
      • EncryptionKey - string - Gets or Sets the key or password used to encrypt the exported dump file.
      • SaltSize - int - Gets the length of salt used in encryption.
      • AddCreateDatabase - bool - Gets or Sets a value indicates the SQL statement of "CREATE DATABASE" should added into dump file.
      • ExportTableStructure - bool - or Sets a value indicates the Table Structure (CREATE TABLE) should be exported.
      • ResetAutoIncrement - bool - Gets or Sets a value indicates the value of auto-increment of each table should be reset to 1.
      • ExportRows - bool - Gets or Sets a value indicates the Rows should be exported.
      • MaxSqlLength - Gets or Sets the Maximum Length allowed for multiple INSERT SQL statements to join. Default value is 1MB.
      • ExportStoredProcedures - bool - Gets or Sets a value indicates whether the Stored Procedures should be exported.
      • ExportFunctions - bool - Gets or Sets a value indicates whether the Stored Functions should be exported.
      • ExportTriggers - bool - Gets or Sets a value indicates whether the Stored Triggers should be exported.
      • ExportViews - bool - Gets or Sets a value indicates whether the Stored Views should be exported.
      • ExportEvents - bool - Gets or Sets a value indicates whether the Stored Events should be exported.
      • CompleteArg - ExportCompleteArg - The event arguments of ExportCompleted.
      • ZipOutputFile - Gets or Sets a value indicates whether the exported Sql Dump File should be compressed as Zip file. 
  • ImportInfo  - ImportInformations - Gets or Sets the Informations that define behaviour of Import Process.
    • Properties, Methods and Fields
      • FileName - string - Gets or Sets the full path and file name (dump file) that will be imported.
      • AsynchronousMode - bool - Gets or Sets a value indicates whether the Import process should run in Asynchronous Mode.
      • AutoCloseConnection - bool - Gets or Sets a value indicates whether the MySqlConnection and MySqlCommand used should close and dispose after import process finished.
      • EnableEncryption - bool - Gets or Sets a value indicates whether the Imported Dump File is encrypted.
      • EncryptionKey - string - Gets or Sets the key or password used to decrypt the exported dump file.
      • SaltSize - int - Gets the lenght of salt used in encryption.
      • SetTargetDatabase(string, string) - Set the target database name that will be imported to and the default character set. If the database if not exists, it will be created.
      • SetTargetDatabase(string) - Set the target database name that will be imported to. If the database if not exists, it will be created. The default character set of current connecting MySQL server will be used as default character set for this new target database.
      • SetTargetDatabase(string, Enum) - the target database name that will be imported to and the default character set. If the database if not exists, it will be created.
      • CreateTargetDatabaseSql - Gets the CREATE DATABASE SQL statement of current database.
      • TargetDatabase - string - Gets the name of target database.
      • IgnoreSqlError - bool - Gets or Sets a value indicates whether SQL errors occus in import process should be ignored. If true, all errors (exceptions) will be collected in ImportCompleteArg.Errors.
      • CompleteArg - ImportCompleteArg (Event argument of ImportCompleted)

Public Methods

  • Export() - Execute the export (backup) process.
  • Export(ExportInformations) - Execute the export (backup) process. Sets the ExportInformations used by this export process.
  • CancelExport() - Cancel the current executing export process.
  • Import() - Execute the import process.
  • Import(ImportInformations) - Execute the import (restore) process. Sets the ImportInformations about this import process.
  • CancelImport() - Cancel the current executing import process.
  • DeleteAllRows(bool) - Delete all rows in all tables. Sets a value indicates whether Auto-Increment should reset to 1.
  • DeleteAllRows(bool, string[]) - Delete all rows in all tables. Sets a value indicates whether Auto-Increment should reset to 1. Exclude these tables from rows deletion.
  • EncryptSqlDumpFile(string, string) - Encrypt a SQL Dump File and save as new file.
  • DecryptSqlDumpFile(string, string) - Decrypt a SQL Dump File and save as new file.
  • ExportBlobAsFile(string, string, string, string, string) - Export BLOB data type and save as file.
  • Dispose() - Release all resources used by this instance.
  • Dispose(bool) - Release all resources used by this instance. Determine whether MySqlConnection and MySqlCommand used by this instance should dispose.

Events

  • ExportProgressChanged - Occur when a row of data is exported or calculation of total rows of a table is completed.
    • Event Arguments:
      • CurrentTableName - String
      • TotalRowsInCurrentTable - Long
      • TotalRowsInAllTables - Long
      • CurrentRowInCurrentTable - Long
      • CurrentRowInAllTable - Long
      • TotalTables - Int
      • CurrentTableIndex - Int
      • PercentageCompleted - Int
      • PercentageGetTotalRowsCompleted - Int
  • ExportCompleted - Occur when Export processs is finished.
    • Event Arguments:
      • TimeStart - DateTime
      • TimeEnd - DateTime
      • TimeUsed - TimeSpan
      • Error - Exception (Error that occur during the process)
      • CompletedType - Enum (Completed, Cancelled, Error)
  • ImportProgressChanged - Occur when a line in the dump file is imported.
    • Event Arguments:
      • CurrentByte - Long
      • TotalBytes - Long
      • Error - Exception (The error information that encounter.)
      • CurrentLineNo - Long
      • ErrorSql - String (The SQL statement that creates the error)
      • PercentageCompleted
  • ImportCompleted - Occur when Import process is finished.
    • Event Arguments:
      • TimeStart - DateTime
      • TimeEnd - DateTime
      • TimeUsed - TimeSpan
      • CurrentLineNo - Long
      • HasErrors - Bool
      • LastError - Exception (The last error (exception) occur in import process.)
      • CompletedType - Enum (Completed, Cancelled, Error)
      • Errors - Dictionary<long, Exception> (The collection of errors. Exceptions will be collected if Ignore SQL Error has set to true in Import Info.)

6. Adding MySqlBackup.NET Into Your Project

Before using this library, you must add a reference of MySQL Dot Net Connector (MySql.Data.DLL). You can get the lastest MySql Dot Net Connector at: [http://dev.mysql.com/downloads/connector/net/].

There are a few easy way to add MySqlBackup.NET in your C# (WinForm, ASP.NET) application. 

1st method, (Note: it is available, but not updated to latest version yet) using the Nuget (https://nuget.org/packages/MySqlBackup.NET). At the Package Manager Console of Nuget in Visual Studio, key in the below command, it will automatically download and install MySqlBackup.NET into your project.

 PM> Install-Package MySqlBackup.NET 

2nd method, add all the CS files into your source code directly. Source code available at top of this article. 

Create a folder and add the CS files: 

 

At top of your cs file, add this line:

using MySql.Data.MySqlClient;

Using in VB.NET,

You can use Nuget to help you. If you want to do it manually, you have to compile the library into a DLL and add it as reference into your VB.NET project.

  


7. Basic Examples

Example 1: Backup

void Backup()
{
    string constr = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\\MyDumpFile.sql";
    MySqlBackup mb = new MySqlBackup(constr);
    mb.ExportInfo.FileName = file;
    mb.Export();
}

Example 2: Restore

Note: The source file can be either a SQL Dump file or Compressed Zip file. 

void Restore()
{
    string constr = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\\MyDumpFile.sql";
    MySqlBackup mb = new MySqlBackup(constr);
    mb.ImportInfo.FileName = file;
    mb.Import(); 
}

Example 3: Export and Compress as Zip File

Note: You can use a compressed SQL Dump File in Zip format as source file directly to restore a database. 

void Backup()
{
    string constr = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\\MyDumpFile.sql";
    MySqlBackup mb = new MySqlBackup(constr);
    mb.ExportInfo.FileName = file;
    mb.ExportInfo.ZipOutputFile = true;
    mb.Export();
}  

Example 4: Select tables to backup

void BackupTables()
{
    string constr = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\\MyDumpFile.sql";
    MySqlBackup mb = new MySqlBackup(constr);
    mb.ExportInfo.FileName = file;
    mb.ExportInfo.TablesToBeExported = new string[] { "member", "activity", "season" };
    mb.Export();
}

Example 5: Custom columns and rows backup conditions

void BackupTablesCustomSQL()
{
    Dictionary<string, string> dic = new Dictionary<string, string>();
    dic.Add("member", "SELECT * FROM `member` WHERE `membertype` = 1;");
    dic.Add("payment", "SELECT `id`,`total` FROM `payment`;");
    dic.Add("activity", "SELECT * FROM `activity` a INNER JOIN `season` s ON a.`seasonid` = s.`id` WHERE s.`name` = 'Spring';");
    string constr = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\\MyDumpFile.sql";
    MySqlBackup mb = new MySqlBackup(constr);
    mb.ExportInfo.FileName = file;
    mb.ExportInfo.TableCustomSql = dic;
    mb.Export();
}

Example 6: Backup with Encryption

void BackupEncrypt()
{
    string constr = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\\MyDumpFile.sql";
    MySqlBackup mb = new MySqlBackup(constr);
    mb.ExportInfo.FileName = file;
    mb.ExportInfo.EnableEncryption = true;
    mb.ExportInfo.EncryptionKey = "my secret password";
    mb.Export();
}

Example 7: Resotre with Decryption

void RestoreDecrypt()
{
    string constr = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\\MyDumpFile.sql";
    MySqlBackup mb = new MySqlBackup(constr);
    mb.ImportInfo.FileName = file;
    mb.ImportInfo.EnableEncryption = true;
    mb.ImportInfo.EncryptionKey = "my secret password";
    mb.Import(); 
}

Example 8: Encrypt & Decrypt a SQL Dump File

void EncryptDecryptDumpFile()
{
    MySqlBackup mb = new MySqlBackup();
    string file1 = "C:\\MyDumpFileOld.sql";
    string file2 = "C:\\MyDumpFileNew.sql";
    string file3 = "C:\\MyDumpFileBackToOri.sql";
    string password = "my secret password";
    mb.EncryptSqlDumpFile(file1, file2, password);
    mb.DecryptSqlDumpFile(file2, file3, password);
}

Example 9: Backup Table Structures without rows and reset auto-increment to 1

void BackupNoRows()
{
    string constr = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\\MyDumpFile.sql";
    MySqlBackup mb = new MySqlBackup(constr);
    mb.ExportInfo.FileName = file;
    mb.ExportInfo.ExportRows = false;
    mb.ExportInfo.ResetAutoIncrement = true;
    mb.Export();
}

Example 10: Full List of Settings for Export (Backup)

There are some more settings which affect the output results of Export Process. All of these settings are configured in ExportInfo. A full list of settings:

void BackupNoRows()
{
    string constr = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\\MyDumpFile.sql";
    MySqlBackup mb = new MySqlBackup(constr);
    mb.ExportInfo.FileName = file;
    mb.ExportInfo.AddCreateDatabase = true;
    mb.ExportInfo.AsynchronousMode = true;
    mb.ExportInfo.AutoCloseConnection = true;
    mb.ExportInfo.CalculateTotalRowsFromDatabase = true;
    mb.ExportInfo.EnableEncryption = true;
    mb.ExportInfo.EncryptionKey = "my secret password";
    mb.ExportInfo.ExportEvents = true;
    mb.ExportInfo.ExportFunctions = true;
    mb.ExportInfo.ExportRows = true;
    mb.ExportInfo.ExportStoredProcedures = true;
    mb.ExportInfo.ExportTableStructure = true;
    mb.ExportInfo.ExportTriggers = true;
    mb.ExportInfo.ExportViews = true;
    mb.ExportInfo.MaxSqlLength = 10000000;
    mb.ExportInfo.RecordDumpTime = true;
    mb.ExportInfo.ResetAutoIncrement = true;
    mb.ExportInfo.TableCustomSql = //Shown in example 4
    mb.ExportInfo.TablesToBeExported = //Shown in example 3
    mb.ExportInfo.ExportRows = false;
    mb.ExportInfo.ResetAutoIncrement = true; 
    mb.ExportInfo.ZipOutputFile = false;
    mb.Export();
} 

Example 11: Full List of Settings for Import

void Restore()
{
    string constr = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\\MyDumpFile.sql";
    MySqlBackup mb = new MySqlBackup(constr);
    mb.ImportInfo.FileName = file;
    mb.ImportInfo.AsynchronousMode = true;
    mb.ImportInfo.AutoCloseConnection = true;
    mb.ImportInfo.EnableEncryption = true;
    mb.ImportInfo.EncryptionKey = "my secret password";
    mb.ImportInfo.IgnoreSqlError = true;
    mb.ImportInfo.SetTargetDatabase("MyNewDatabase", ImportInformations.CharSet.latin1);
    mb.Import(); 
}

Example 12: Export BLOB data and save as files on local drive

private void BackupEncrypt()
{
    string folder = "C:\\exportedfiles";
    string table = "upload";
    string column_Blob = "blobdata";
    string column_FileName = "filename";
    string column_FileSize = "filesize";
    string con = "server=localhost;user=root;pwd=qwerty;database=member;";
    MySqlBackup mb = new MySqlBackup(con);
    mb.ExportBlobAsFile(folder, table, column_Blob, column_FileName, column_FileSize);
}

Example 13: Get all tables' name from database

private string[] GetTableNames()
{
    string con = "server=localhost;user=root;pwd=qwerty;database=test;";
    MySqlBackup mb = new MySqlBackup(con);
    return mb.DatabaseInfo.TableNames;
}

Example 14: Get Create Table sql statement for specific table

private string GetCreateTable(string tableName)
{
    string con = "server=localhost;user=root;pwd=qwerty;database=test;";
    MySqlBackup mb = new MySqlBackup(con);
    return mb.DatabaseInfo.Tables[tableName].CreateTableSql;
}

8. Examples of Using MySqlBackup.NET in ASP.NET 

MySqlBackup.NET need to access a physical file on disk to perform task. We can use Server.MapPath to provide a physical path for MySqlBackup.NET. 

Backup MySQL Database 

void Backup()
{
    string connection = "server=localhost;user=root;pwd=qwerty;database=test;";
    string fileOnDisk = HttpContext.Current.Server.MapPath("~/MyDumpFile.sql");
    // Example Result: C:\inetpub\wwwroot\MyDumpFile.sql
    string fileOnWeb = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) 
                       + "/MyDumpFile.sql";
    // Example Result: http://www.mywebsite.com/MyDumpFile.sql

    MySqlBackup mb = new MySqlBackup(connection);
    mb.ExportInfo.FileName = fileOnDisk;
    mb.Export();
    // Download the file
    Response.ContentType = "text/plain";
    Response.AppendHeader("Content-Disposition", "attachment; filename=MyDumpFile.sql");
    Response.TransmitFile(fileOnDisk);
    Response.End();
} 

Restore MySQL Database 

void Restore()
{
    string connection = "server=localhost;user=root;pwd=qwerty;database=test;";
    string fileOnDisk = HttpContext.Current.Server.MapPath("~/MyDumpFile.sql");
    string fileOnWeb = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) 
                       + "/MyDumpFile.sql";
    // Upload the file
    if (FileUpload1.HasFile)
    {
        FileUpload1.SaveAs(fileOnDisk);

        MySqlBackup mb = new MySqlBackup(connection);
        mb.ImportInfo.FileName = fileOnDisk;
        mb.Import();
        Response.Write("Import Successfully");
    }
}

9. About Synchronous And Asynchronous Mode 

Switching between Asynchronous and Synchronous Mode is a new feature in V1.5.

By default, all process run in Synchronous Mode (Single Thread).

To execute Export (Backup) process in Asynchronous Mode:

void Backup(string connection, string file)
{
    MySqlBackup mb = new MySqlBackup(connection);
    mb.ExportInfo.FileName = file;
    mb.ExportInfo.AsynchronousMode = true;
    mb.Export();
}

Asynchronous Mode prevents WinForm UI to freeze. The animation of Progress Bar continues to move while the export or import process running in background. On the other hand, in Asynchronous Mode, you have the choice to cancel/halt the export or import process and you can't do it in Synchronous Mode.

However, in Web Application or Web Service, there is no differences for the process runs either in Asynchronous or Synchronous Mode. This is because the main thread will still need to be suspended.

If you have a small database, the whole process will be completed in less than 1 second. In such situation, running the process in Asynchronous Mode might not be necessary.


10. Using MySqlBackup.NET with Progress Bar

Progress reporting is a new feature in V1.3. This enable the usage of Progress Bar.

Simple Walk Through 

  1. MySqlBackup.NET will raise an Event (ExportProgressChanged or ImportProgressChanged) after a row or a line of data is processed.
  2. The Event carries a bunch of values indicating the current processing point.
  3. These values are loaded into a temporary storage location.
  4. Use a Timer (Timer1) to read the values from temporary storage location and load it into Progress Bar repeatedly.
  5. Upon the process is finished, cancelled or encounter error, another Event will raised (ExportCompleted or ImportCompleted) indicating the termination.
  6. Use another Timer (Timer2) to stop Timer1.

Detail Walk Through

This guide is shown in WinForm.

Start by adding this line at the top of the form class.

using MySql.Data.MySqlClient; 

This is what we have initially with a new WinForm.

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}

Declare some fields for storing the progress value, an instance of MySqlBackup and 2 timers.

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        // Temporary Storage Location
        string CurrentTableName = "";
        long TotalRowsInCurrentTable = 0;
        long TotalRowsInAllTables = 0;
        long CurrentRowInCurrentTable = 0;
        long CurrentRowInAllTable = 0;
        int TotalTables = 0;
        int CurrentTableIndex = 0;
        int PercentageComplete = 0;
        int PercentageGetTotalRowsCompleted = 0;

        MySqlBackup mb;

        Timer timerRead;
        Timer timerStop;

        bool stopTimer1 = false;

        public Form1()
        {
            InitializeComponent();
        }
    }
}

Build the Backup method. 

void Backup()
{
    string constr = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\\MyDumpFile.sql";
    MySqlBackup mb = new MySqlBackup(constr);
    mb.ExportInfo.FileName = file;
    mb.ExportProgressChanged += new MySqlBackup.exportProgressChange(mb_ExportProgressChanged);
    mb.ExportCompleted += new MySqlBackup.exportComplete(mb_ExportCompleted);
    timerRead.Start();
    mb.Export();
}

void mb_ExportCompleted(object sender, ExportCompleteArg e)
{
    throw new NotImplementedException();
}

void mb_ExportProgressChanged(object sender, ExportProgressArg e)
{
    throw new NotImplementedException();
}

During event of ExportProgressChanged, load values into temporary storage location:

void mb_ExportProgressChanged(object sender, ExportProgressArg e)
{
    PercentageGetTotalRowsCompleted = e.PercentageGetTotalRowsCompleted;
    PercentageComplete = e.PercentageCompleted;
    CurrentTableName = e.CurrentTableName;
    TotalRowsInCurrentTable = e.TotalRowsInCurrentTable;
    TotalRowsInAllTables = e.TotalRowsInAllTables;
    CurrentRowInCurrentTable = e.CurrentRowInCurrentTable;
    CurrentRowInAllTable = e.CurrentRowInAllTable;
    TotalTables = e.TotalTables;
    CurrentTableIndex = e.CurrentTableIndex;
}

Use a Timer (timerRead) to read the values into Progress Bar.

public Form1()
{
    InitializeComponent();
    timerRead = new Timer();
    timerRead.Interval = 100; // Refresh Progress Bar 10 times in 1 second
    timerRead.Tick += new EventHandler(timerRead_Tick);
}

void timerRead_Tick(object sender, EventArgs e)
{
    progressBar_PercentComplete.Maximum = 100;
    progressBar_PercentComplete.Value = PercentageComplete;

    progressBar_Table.Maximum = TotalTables * 10;
    progressBar_Table.Value = CurrentTableIndex * 10;

    progressBar_RowsDB.Maximum = (int)TotalRowsInAllTables;
    progressBar_RowsDB.Value = (int)CurrentRowInAllTable;

    progressBar_RowsTable.Maximum = (int)TotalRowsInCurrentTable;
    progressBar_RowsTable.Value = (int)CurrentRowInCurrentTable;
}

You may add another method to stop the Export process just in case you need to cancel it.

public void CancelBackup()
{
    mb.CancelExport();
} 

Upon the process is finished or terminated, the final event raise. Call the second timer to stop the first timer. 

void mb_ExportCompleted(object sender, ExportCompleteArg e)
{
    timerStop = new Timer();
    timerStop.Interval = 150;
    timerStop.Tick += new EventHandler(timerStop_Tick);
    timerStop.Start();
}

void timerStop_Tick(object sender, EventArgs e)
{
    timerStop.Stop();
    timerRead.Stop();
}

We do not stop the first timer immediately. This will allow the first timer able to catch up the last value raised. Or else, the Progress Bar might (might not) showing 99% completed in stead of 100%. Notice that the interval time for 2nd timer is a bit longer than 1st timer. The reason is the same.


11. Gathering Information After Export/Import Process Completed

After the process completed, some useful information is stored in ExportCompleteArg and ImportCompleteArg.

For Export process, ExportCompleteArg is part of event argument of ExportCompleted. However, if you do not raise the event, you still can access the values in the ExportInformation.

Event of ExportCompleted must be applied in order to get notified when it is finished if you run MySqlBackup.NET in Asynchronous Mode.

Example of accessing ExportCompleteArg:

void BackupWithEvent(string connection, string file)
{
    MySqlBackup mb = new MySqlBackup(connection);
    mb.ExportInfo.FileName = file;
    mb.ExportCompleted += new MySqlBackup.exportComplete(mb_ExportCompleted);
    mb.Export();
}

void mb_ExportCompleted(object sender, ExportCompleteArg e)
{
    ShowMessage(e);
}

void BackupWithNoEvent(string connection, string file)
{
    MySqlBackup mb = null;
    try
    {
        mb = new MySqlBackup(connection);
        mb.ExportInfo.FileName = file;
        mb.Export();
    }
    catch { }
    ShowMessage(mb.ExportInfo.CompleteArg);
}

void ShowMessage(ExportCompleteArg e)
{
    StringBuilder sb = new StringBuilder();
    sb.Append("Export " + e.CompletedType.ToString() + "\r\n");
    sb.Append("Time Start: " + e.TimeStart.ToString() + "\r\n");
    sb.Append("Time End: " + e.TimeEnd.ToString() + "\r\n");
    sb.Append("Time Used: " + e.TimeUsed.Minutes + " m " + e.TimeUsed.Seconds + " s " + e.TimeUsed.Milliseconds + " ms\r\n\r\n");
    if (e.Error != null)
    {
        sb.Append("Error Message:\r\n\r\n");
        sb.Append(e.Error.ToString());
    }
    else
    {
        sb.Append("File save at: " + mb.ExportInfo.FileName);
    }
    MessageBox.Show(sb.ToString());
}

This is same to ImportCompleteArg.

If you have set IgnoreSqlError to true during Import, you can get all the SQL Errors (Exceptions) in

ImportCompleteArg.Errors

or

ImportProgressArg.Error

ImportProgressArg.ErrorSql


12. About Importing (Restoring) to Another/New Database

In V1.5, you can Restore to another database (maybe it is not exists) other than the original database specifies (or not specifies) in the dump file. Here is the example:

void Restore()
{
    string constr = "server=localhost;user=root;pwd=qwerty;";
    string file = "C:\\MyDumpFile.sql";
    MySqlBackup mb = new MySqlBackup(constr);
    mb.ImportInfo.FileName = file;
    mb.ImportInfo.SetTargetDatabase("MyNewDatabase", ImportInformations.CharSet.latin1);
    mb.Import(); 
}

If your database involve with Unicode characters, you have to carefully select the right Default Database Character Set while setting the Target Database. You should always choose Default Character Set that used by the source database of the dump file. Or else, you will experience encoding problems and unable to use the database properly. In some cases, you might even cannot INSERT unicode characters correctly into the database.


13. MySqlBackup.dll V1.1

There is a guide shows the design of MySqlBackup.dll version 1.1. You can read it here [the previous old revision of this article - revision 20, posted on 26 Nov 2011] or here [The Basic Ideas].  The above guide describes the methods and design used in MySqlBackup.dll version 1.1. Version 1.2 has a large changes. However, the basic concept is almost the same. The guide includes:
  1. How to collect CREATE DATABASE sql statement.
  2. How to collect CREATE TABLE sql statements for each table. 
  3. How to build INSERT sql statements for each row in each table.
  4. Writes the collected sql statements into SQL Dump File.
  5. Reads the SQL Dump File and execute the sql statements.

Although the guide is for the older version (V1.1), but the guide contains some valuable information on backing up MySQL database manually.


14. Frequently Asked Questions (FAQ) 

1. Cannot connect to website database. An exception Occur: Unable to connect to any of the specified MySQL hosts 

By default, MySql at web hosting will only allow connection from "localhost". If you wish to connect to MySql using your computer (remote access), or other IP, you have to allow the MySql at your website to be connected by the specific IP (your IP). If the website is using CPanel, you may refer this guide:

2. MySql.Data.Types.MySqlConversionException: Unable to convert MySQL date/time value to System.DateTime

This is not a bug. It is an expected behavior. MySQL allow zero date time which means 0 year 0 month and 0 days, but in .NET world's concept, there is no such 0 year, 0 month and 0 day. The minimum possible date in .NET is 01-01-01. (Commonly occur when data type of "DATE" (not DATETIME) used in one of the table). 

There are 2 ways to resolve this:

1st, by adding allowzerodatetime in the MySQL connection string (Recommended if you use MySqlBackup

server=localhost;user=root;pwd=qwerty;database=test;allowzerodatetime=true;

2nd, by adding convertzerodatetime in MySQL connection string.

server=localhost;user=root;pwd=qwerty;database=test;convertzerodatetime=true

3. How do I get notified if there is new release?

You can, by signing up the release notification at http://mysqlbackupnet.codeplex.com/releases 


15. Development of this Project

You are welcome to improve / enhance the project.

Please visit the project hosting site: http://mysqlbackupnet.codeplex.com


16. History 

25 Jan 2013 - Release of V1.5.7 

 ... 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

About the Author

adriancs
Software Developer
Malaysia Malaysia
Another guy from Sabah.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
BugSystem.argumentOutOffRange exceptionmembervrushali katkade5-Jun-13 0:52 
when i will take backup of mysql database it will show the following exception
 
System.argumentOutOffRange exception : Year,Month & day parameters describe an unrepresentable DateTime
at system.Datetime.DatetiTicks(Int32 year,Int32 Month,Int32 day)
at system.Datetime...ctor(int32 year,Int32 Month,Int32 day,int32 hour,int32 minute ,int32 second,int32 milllisecond,datetimekind kind)
at mysql.data.types.mysqlDatetime.GetDatetime();
at mysql.data.mysqlclient.mysqldatareader.getValue(int32 i)
at mysql.data.mysqlclient.mysqldatareader.get_item(int32 i)
at mysql.data.mysqlclient.mysqldatareader.getsqlvaluestring(mysqldatareader rdr)
at mysql.data.mysqlclient.mysqlbackup.ExportStart()
at mysql.data.mysqlclient.mysqlbackup.ExportExecute()

GeneralMy vote of 5memberFabricio Rodrigues10-Apr-13 13:49 
Muito BOM! Parab�ns
QuestionTablesToBeExportedmembermilos stojmenovic28-Feb-13 7:50 
I think I found a small bug in ExportInformation.cs:
 
the line: TableCustomSql = new Dictionary(); is missing on line 65. The code crashes when specifying tables to backup without this line.
 
Using .Net 4.0
 
set
{
    if (value != null && value.Length > 0)
    {
        TableCustomSql = new Dictionary<string, string>();
        foreach (string s in value)
        {
            TableCustomSql.Add(s, string.Format("SELECT * FROM `{0}`;", s));
        }
    }
    else
    {
        TableCustomSql = null;
    }
}

QuestionCompatible with mysqldump?memberFindel12-Feb-13 12:17 
Are the backup files created by MySqlBackup.NET compatible with mysqldump? (meaning I could restore using mysqldump)
 
And can MySqlBackup.NET restore a file created using mysqldump?
 
If so, that is awesome and just what I'm looking for.
QuestionProblem with charsetmemberdawc1599511-Feb-13 2:31 
Hello, first I wanna say thanks for this great library, is really really useful.
 
Now my problem... With this new version I've been having a few issues with the charset of my database; I'm using latin1_spanish_ci on every table and on the database itself, when I make a backup everything goes fine... the problem is when I try to restore, every accented letter and every char like "ñ,ç... etc" it turns into another thing.
My code is based on the application demo and I'm choosing the charset I need before make any import.
 
Hope you can help me with this issue.
 
Thanks in advance and sorry if my english level is kinda poor.
QuestionVb.Netmemberlutzmann9-Jan-13 1:34 
Hallo,
 

Can anyone give me an example for call for vb.net? Roll eyes | :rolleyes:
 
mb.ExportProgressChanged += new MySqlBackup.exportProgressChange(mb_ExportProgressChanged);
 

 
Lutz
AnswerRe: Vb.Netmvpadriancs12-Jan-13 21:18 
this may answer your question:
http://stackoverflow.com/questions/13194056/delegate-error-when-converting-c-sharp-to-vbnet[^]
AnswerRe: Vb.Netmvpadriancs25-Jan-13 2:49 
Hi, demo is available in VB.NET. Download available at top of this article.
GeneralMy vote of 5memberMihai MOGA14-Dec-12 5:44 
This is a great inspiring article. I am pretty much pleased with your good work. You put really very helpful information. Keep it up once again.
QuestionSmall changes in CodememberLaFoo11-Dec-12 22:33 
A really nice and useful library, thanks for your work!
 
I had some problems, e.g. reading the table structure from the MySQL-DB. So I had to change some parts of your code (e.g. in Methods.cs) a little from
 
public string GetCreateTableSql(string table, MySqlCommand cmd)
{
              cmd.CommandText = "SHOW CREATE TABLE `" + table + "`;";
              MySqlDataAdapter da = new MySqlDataAdapter(cmd);
              DataTable dt = new DataTable();
              da.Fill(dt);
              da = null;
              string createSql = dt.Rows[0][1].ToString().Replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS").Replace("\n", "\r\n") + ";";
              return createSql;
}
 
to
public string GetCreateTableSql(string table, MySqlCommand cmd)
{
            cmd.CommandText = "SHOW CREATE TABLE `" + table + "`;";
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            da = null;
 
            byte[] tempBytes = (byte[])dt.Rows[0][1];
            System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
            string tempString = enc.GetString(tempBytes);
 
            string createSql = tempString.Replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS").Replace("\n", "\r\n") + ";";
            
            return createSql;
}
 
Using the original code I found some strings "System.Byte[]" instead of the correct SQL-Statement in the exported sql-File. So there seems to be (sometimes) a problem with encoding/conversion. For example
dt.Rows[0][1].ToString()
returned the string "System.Byte[]" instead of a string containing the table structure. I had the same problems in the part of your code, where the SQL-Statements for Stored Procedures are created.
 
Maybe this helps others.
 
Best regards
AnswerRe: Small changes in Codememberadriancs12-Dec-12 0:04 
So, in some unknown situations, the connector or MySQL server will return a byte[] in stead of string.
 
I faced this problem before when using MySQL's hash function.
Example of MySQL Hash Function:
SELECT PASSWORD('1234');
SELECT MD5('1234');
SELECT SHA('1234');
In older version MySql.Data.DLL, the hash functions return byte[].
I have to do this to get the string:
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
string hash= enc.GetString(tempBytes);
but, in newer version MySql.Data.DLL, the functions return as string.
 
So, back to your problem.
Is this problems is caused by the version of connector too? Which version of MySql.Data.DLL are you using?
 
Anyway, as a solution to this matter, the block of code will be modified as follow:
public string GetCreateTableSql(string table, MySqlCommand cmd)
{
    cmd.CommandText = "SHOW CREATE TABLE `" + table + "`;";
    MySqlDataAdapter da = new MySqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    da = null;
 
    string createSql = "";
    object ob = dt.Rows[0][1];
    if (ob is System.String)
    {
        createSql = ob + "";
    }
    else if (ob is System.Byte[])
    {
        System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
        createSql = enc.GetString((byte[])ob);
    }
 
    return createSql.Replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS").Replace("\n", "\r\n") + ";";
}
and this will be applied too in getting structure of Stored Procedures, Stored Functions, Triggers, etc.
GeneralRe: Small changes in CodememberLaFoo12-Dec-12 1:37 
Thanks for your reply.
I get the same results with MySql.Data.DLL versions 6.2.3.0 and the current 6.6.4.0.
Good to know that there might be different behaviours across the DLL versions.
GeneralRe: Small changes in Codememberadriancs13-Dec-12 20:15 
The above code has been merged into version of 1.5.6.
Download available at top. You may want to review it.
BugThere is already an open DataReader associated with this Connection which must be closed firstmembergillesmaire6-Nov-12 3:47 
Hi,
 
When i would like ti test the component i have this error :
 
"There is already an open DataReader associated with this Connection which must be closed first"
 
Here is my test code :
 
MySqlBackup mb = new MySqlBackup((MySqlConnection)GenericApplicationContext.DbConnection);
 
the error occur in Database.cs line 138
 
public Database(ref MySqlCommand cmd)
        {
            StoredEvents = new Dictionary<string, string>();
            StoredFunction = new Dictionary<string, string>();
            StoredProcedure = new Dictionary<string, string>();
            StoredTrigger = new Dictionary<string, string>();
            StoredView = new Dictionary<string, string>();
            Tables = new Dictionary<string, Table>();
 
            if (cmd.Connection.State != ConnectionState.Open)
                cmd.Connection.Open();
 
            cmd.CommandText = "SELECT DATABASE();";
            _databaseName = cmd.ExecuteScalar().ToString();
 
Regards,
Gilles
GeneralRe: There is already an open DataReader associated with this Connection which must be closed firstmemberadriancs6-Nov-12 13:42 
You can try to find out is there any DataReader associated with this connection:
GenericApplicationContext.DbConnection
before it is passed into MySqlBackup.
Do you make any queries by using the connection before MySqlBackup?
GeneralRe: There is already an open DataReader associated with this Connection which must be closed firstmembergillesmaire7-Nov-12 21:15 
Yes, i have other queries before but with this syntax :
 
DataSet ds = new DataSet();
DbCommand dbCommand = GenericDbProviderFactory.GetDbCommand(GetSearchRequest(), GetConnection());
DbDataAdapter MyAdapter = GenericDbProviderFactory.CreateDbDataAdapter(GenericApplicationContext.DriverBdd);
MyAdapter.SelectCommand = dbCommand;
MyAdapter.Fill(ds);
return ds;
 
and i cas use this after for other command without problem
 
:(
GeneralRe: There is already an open DataReader associated with this Connection which must be closed firstmemberadriancs6-Nov-12 21:18 
You can try this:
((MySqlConnection)GenericApplicationContext.DbConnection).Close();
((MySqlConnection)GenericApplicationContext.DbConnection).Open();
MySqlBackup mb = new MySqlBackup((MySqlConnection)GenericApplicationContext.DbConnection);

GeneralRe: There is already an open DataReader associated with this Connection which must be closed firstmembergillesmaire7-Nov-12 21:10 
Thanks for your answer but it doesn't work :(
GeneralRe: There is already an open DataReader associated with this Connection which must be closed firstmemberadriancs7-Nov-12 22:55 
Try submit a sample project that creates the error at here:
http://mysqlbackupnet.codeplex.com/workitem/list/basic[^]
GeneralRe: There is already an open DataReader associated with this Connection which must be closed firstmemberadriancs30-Dec-12 19:17 
Hi, try this:
MySqlBackup mb = new MySqlBackup(GenericApplicationContext.DbConnection.ConnectionString);

SuggestionInteresting but ... MySql?memberBlackMilan24-Oct-12 0:10 
Hi,
 
Let's think out of the box for a moment. - Oh, there's another database ... named MySql, ups! OMG | :OMG:
 
So I'm afraid your naming conventions are a little bit inconvenient. :(
GeneralRe: Interesting but ... MySql? [modified]memberadriancs24-Oct-12 1:18 
You mean, the naming should be MySQL, not MySql.
Is this what you are trying to tell me?
 
Explanation:
I'm following the standard naming system of MySQL dot net connector (Connector/NET).
The naming system is begin with MySqlxxxxxxxx.
 
example:
MySqlConnection
MySqlCommand

 
the namespace of MySQL Dot Net Connector is also begin with MySql
 
MySql.Data.MySqlClient


modified 24-Oct-12 7:25am.

GeneralRe: Interesting but ... MySql?memberBlackMilan24-Oct-12 3:37 
Sorry, shame on me! I thought you'll backup a SQL server.
From now, I see my mistake. :(
GeneralMy vote of 5memberJack_32119-Oct-12 3:13 
really good writing Smile | :)
QuestionNo ExportInfomemberDThought17-Oct-12 19:41 
I have installed this into my windows form project by way of NuGet, but when following some of your sample source I get errors when trying to use both "mb.ExportInfo" and "mb.Export()".
 
For some reason the ExportInfo does not exist and the empty Export() is not a method.
 
The version installed via NuGet is 1.4.5.0, do I have to have a newer version for these things to be included?
AnswerRe: No ExportInfomemberadriancs17-Oct-12 19:54 
Hi, the package in NuGet has not updated to the latest version. I'll resolve this as soon as possible. (Its currently managed by another team member).
 
I'll inform you once the packages in NuGet is updated by replying this message.
 
Currently, you can download the source code and add it directly into your project.
Smile | :)
Questionproblem when exporting procedures and triggersmemberDESIRE.NTAHIMPERA15-Oct-12 10:43 
I 'm trying to export procedures ,procedures ,views but i still cannot achieve this.
I have set the attribute mb.ExportInfo.exportStoredProcedure to true but nothing happen.
AnswerRe: problem when exporting procedures and triggersmemberadriancs15-Oct-12 15:46 
Do you have procedures and triggers created in database?
 
try executing these codes:
void TestProcedureView()
{
    string file = "C:\\TestDump.sql";
    string constr = "server=localhost;user=root;pwd=1234;database=test;";
    string createView = "CREATE VIEW `myview` AS SELECT 'Hello View!';";
    string createProcedure = "DELIMITER | CREATE PROCEDURE `myprocedure`() DETERMINISTIC BEGIN SELECT 'Hello Procedure!'; END|";
 

    using (MySqlConnection conn = new MySqlConnection(constr))
    {
        conn.Open();
        MySqlScript ms = new MySqlScript(conn);
        ms.Query = createProcedure;
        ms.Execute();
        MySqlCommand cmd = new MySqlCommand(createView, conn);
        cmd.ExecuteNonQuery();
        conn.Close();
    }
 
    MySqlBackup mb = new MySqlBackup(constr);
    mb.ExportInfo.FileName = file;
    mb.ExportInfo.ExportTableStructure = false;
    mb.ExportInfo.ExportRows = false;
    mb.Export();
}
then, open C:\TestDump.sql
and notice the content.
GeneralRe: problem when exporting procedures and triggersmemberDESIRE.NTAHIMPERA15-Oct-12 21:21 
Thank you for your response but when i execute your code this is what i get
 
-- MySqlBackup.NET dump 1.5 beta
-- Dump time: 2012-10-16 09:18:09
-- ------------------------------------------------------
-- Server version   5.5.8-log MySQL Community Server (GPL)
 

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES latin1 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
 

/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

GeneralRe: problem when exporting procedures and triggersmemberadriancs15-Oct-12 22:38 
This is the result that should produce by executing the above codes:
-- MySqlBackup.NET dump 1.5 beta
-- Dump time: 2012-10-16 15:31:53
-- ------------------------------------------------------
-- Server version	5.5.25 MySQL Community Server (GPL)

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES latin1 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
 
--
-- Dumping stored procedures
--

DROP PROCEDURE IF EXISTS `myprocedure`;
DELIMITER |
CREATE DEFINER=`root`@`localhost` PROCEDURE `myprocedure`()
    DETERMINISTIC
BEGIN SELECT 'Hello Procedure!'; END|
DELIMITER ;
 
--
-- Dumping views
--

DROP VIEW IF EXISTS `myview`;
CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `myview` AS select 'Hello View!' AS `Hello View!`;
 
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
I'm currently not sure why is this happening. I need more details information to diagnose the cause of problem. Perhaps it might (might not) cause by user privilege. Is the user account that you used to connect to MySQL database has super privilege? (administrator privilege)
GeneralRe: problem when exporting procedures and triggersmemberDESIRE.NTAHIMPERA16-Oct-12 0:49 
I'm using the default user root without password.
Let's me create an new user with administrator privileges and a password
I give feed back.
GeneralRe: problem when exporting procedures and triggersmemberadriancs18-Oct-12 17:24 
Hi, a new Database Analyser is added into MySqlBackup Demo and Diagnosis Tools 3.1. It can help to analyse your database. Read more at: Analysis of Database for Backup And Restore Operation[^]
GeneralMy vote of 5memberAlbarhami24-Sep-12 19:38 
Great sequential information
GeneralMy vote of 5memberAbinash Bishoyi24-Sep-12 14:10 
Nice
GeneralClaim you contribution adriancs at ohlohmemberAbinash Bishoyi24-Sep-12 14:07 
I have added the project to the Ohloh https://www.ohloh.net/p/MySqlBackupNET
GeneralMy vote of 3memberphoohtoo23-Sep-12 23:58 
good
Questionencryptmemberphoohtoo23-Sep-12 23:58 
i can't encrypt mysql stored procedures ..
 
why?
AnswerRe: encryptmemberGarth J Lancaster24-Sep-12 0:18 
That's a pretty rude way of expressing an issue with free software.
 
How would the author (or anyone else for that matter) know how to answer your question, unless you posted code showing what you attempted to do, and show what errors etc you received, hmmm ??
 
'g'
GeneralRe: encryptmemberphoohtoo24-Sep-12 0:21 
SORRY..
the error i got is as the following..
<pre lang="SQL">
MySql.Data.MySqlClient.MySqlException (0x80004005): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER |
CREATE DEFINER=`root`@`localhost` PROCEDURE `AccountSelect`()
BEGIN' at line 1
at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int32& insertedId)
at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int32& insertedId)
at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
at MySql.Data.MySqlClient.MySqlBackup.bwImport_DoWork(Object sender, DoWorkEventArgs e)
GeneralRe: encryptmemberadriancs14-Oct-12 22:22 
Hi, phoohtoo,
The bug has been fixed. thanks for the bug report. Smile | :)
 
In the dump file, there are 2 types of execution. Script and Single Sql Query.
Script comprise of multi SQL wrap by Delimiter.
Single Sql Query is end by ";".
 
Before a Procedure is created, a DROP PROCEDURE (single query) is called.
 
This bug occur because of the DROP PROCEDURE and CREATE PROCEDURE are encrypted together.
During decryption, MySqlBackup.NET unable to detect the delimeter (because DROP PROCEDURE come first). This block of SQLs is identified as single SQL and is sent to MySqlCommand to execute. As MySqlCommand unable to recognize the query, MySqlCommand raised the SQL syntax error.
 
This bug is fixed by separating the encryption of DROP PROCEDURE and CREATE PROCEDURE.
Therefore, during decryption, DROP PROCEDURE will be decrypted first and identified as single SQL (send to MySqlCommand), follow by decryption of CREATE PROCEDURE and identified as Script (send to MySqlScript).
 
New version(1.5) is available as top. good luck
GeneralRe: encryptmemberphoohtoo16-Oct-12 23:22 
Thanks.
GeneralMy vote of 5mvpKanasz Robert19-Sep-12 4:51 
Well done
GeneralMy vote of 5memberAbinash Bishoyi17-Sep-12 6:20 
Very well written and explained.
GeneralMy vote of 5membersoulprovidergr16-Sep-12 23:09 
I Like this article.
 
I will put it on my favorites to study it
GeneralMy vote of 4mentorMd. Marufuzzaman14-Sep-12 2:02 
Good,
QuestionhelpfulmemberAlbarhami13-Sep-12 4:09 
Thank you
GeneralMy vote of 4memberAlbarhami13-Sep-12 4:09 
a
GeneralMy vote of 5memberjavedsmart11-Sep-12 21:38 
Very well written and explained. My 5.
GeneralRe: My vote of 5memberadriancs12-Sep-12 21:18 
hi, thanks
SuggestionAdditional functionalitymemberNiemand253-Sep-12 22:18 
It would be nice to have these additional functions:
- import/export synchronously (I use web service for BO transfer, asynchronous process wouldn't make any sense as main thread need to be suspended anyway);
- import to certain database that differs from the original.
 
I have written a library for auto upgrading (keeping) DB structure according to a gauge structure in xml file. Could be nice extra functionality for your library. If you are interested I could share it.

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130617.1 | Last Updated 14 Dec 2012
Article Copyright 2012 by adriancs
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid