Auto backup of MySql database
This article will help you to take auto backup of MySql database on timer based. You just set the values in minutes in .ini file that you have created. Than you can change without changing the code to take a backup. Now if you want to the change the backup timing from 5 minutes instead of 1 minute just change the value in file, you are done.
When the application is started database backup will be started automatically till the application is not closed.
First Step:
Create two normal windows form:
Second Step:
Create .ini file with any name that you want. I had give the file name as vsconfig.ini
Third Step:
Set the values in .ini file. so that you can get the values directly from the file. You do not need to change the code. Just change the values in .ini file. Connection will be created based on values of .ini file.
Values to be set in .ini file
database server name -- you can also set the ip address.
database name
database port
backup interval time -- you can set the backup interval time. i have set the 1 minute. so that after every minute while application is running.
database backup path -- i have set the path as D:\MySQLBackup
I have set the values as following:
127.0.0.1
bs2014
3306
1
D:\MySQLBackup
Fourth Step:
Create class file named MySQLBackupRestore.cs than Write the following code in MySQLBackupRestore.cs:
using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using System.IO;
using System.Data;
using System.Drawing;
using System.Configuration;
using System.Windows.Forms;
//using XCrypt;
namespace MySql.Data.MySqlClient
{
class MySqlBackupRestore
{
///
/// Get or Set the Full Path + the Filename to Backup or Restore
///
public string Filename = "";
public string MySQLConnectionString = "";
public string EncryptionKey = "";
public bool Construct_SQL_In_One_Line_From_Same_Table = true;
public string myServer = "";
public string myUser = "";
public string myPassword = "";
public string myDatabase = "";
public string myPort = "";
Form f = null;
ProgressBar progressBar1 = null;
public MySqlBackupRestore()
{ }
public MySqlBackupRestore(string MySqlServer, string MySqlUser, string MySqlPwd, string MySqlDatabase, string MySqlPort)
{
myServer = MySqlServer;
myUser = MySqlUser;
myPassword = MySqlPwd;
myDatabase = MySqlDatabase;
myPort = MySqlPort;
}
public void Backup(string filename)
{
Filename = filename;
Backup();
}
public void Backup()
{
List
string myCon = "";
if (MySQLConnectionString.Length != 0)
myCon = MySQLConnectionString;
else
{
myCon = "server=" + myServer + ";user=" + myUser + ";password=" + myPassword + ";database=" + myDatabase + ";port=" + myPort + ";";
}
//MySqlConnection conn = new MySqlConnection(myCon);
string connect = ConfigurationManager.ConnectionStrings["mycon"].ConnectionString;
MySqlConnection conn = new MySqlConnection(connect);
#region Get all tables' name in database
string sqlcmd = "show tables;";
DataTable dtTable = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(sqlcmd, conn);
da.Fill(dtTable);
#endregion
#region Construct: Create Database SQL command
DataTable dtDatabase = new DataTable();
sqlcmd = "select database();";
da = new MySqlDataAdapter(sqlcmd, conn);
da.Fill(dtDatabase);
string DatabaseName = dtDatabase.Rows[0][0] + "";
dtDatabase = new DataTable();
sqlcmd = "show create database `" + DatabaseName + "`;";
da = new MySqlDataAdapter(sqlcmd, conn);
da.Fill(dtDatabase);
SQLs.Add((dtDatabase.Rows[0][1] + "").Replace("CREATE DATABASE", "create database if not exists") + ";");
SQLs.Add("use `" + DatabaseName + "`;");
#endregion
foreach (DataRow dr in dtTable.Rows)
{
string tablename = dr[0] + "";
#region Backup Each Table's Structure
string sql2 = "show create table `" + tablename + "`;";
DataTable dtCreateTable = new DataTable();
MySqlDataAdapter da2 = new MySqlDataAdapter(sql2, conn);
da2.Fill(dtCreateTable);
string createTable = (dtCreateTable.Rows[0][1] + "").Replace("\n", string.Empty);
SQLs.Add(createTable.Replace("CREATE TABLE", "create table if not exists") + ";");
#endregion
// Delete all rows in table
SQLs.Add("delete from `" + tablename + "`;");
#region Get all column's name in table
DataTable dtColumn = new DataTable();
string sql3 = "show columns from `" + tablename + "`";
MySqlDataAdapter da3 = new MySqlDataAdapter(sql3, conn);
da3.Fill(dtColumn);
#endregion
#region Get all rows in table
DataTable dtRows = new DataTable();
string sql4 = "select * from `" + tablename + "`";
MySqlDataAdapter da4 = new MySqlDataAdapter(sql4, conn);
da4.Fill(dtRows);
#endregion
#region Loop each row and construct sql INSERT command
if (dtRows.Rows.Count != 0)
{
StringBuilder sb = new StringBuilder();
if (Construct_SQL_In_One_Line_From_Same_Table)
sb.AppendFormat("insert into `" + tablename + "` value (");
for (int i = 0; i < dtRows.Rows.Count; i++)
{
if (!Construct_SQL_In_One_Line_From_Same_Table)
sb.AppendFormat("insert into `" + tablename + "` value (");
for (int j = 0; j < dtRows.Columns.Count; j++)
{
string datatype = dtRows.Columns[j].DataType.ToString();
string text = "";
DateTime dtime = DateTime.Now;
if (datatype == "System.DateTime")
{
if (DateTime.TryParse(dtRows.Rows[i][j] + "", out dtime))
{
text = "'" + Convert.ToDateTime(dtRows.Rows[i][j]).ToString("yyyy-MM-dd HH:mm:ss") + "'";
}
else
text = "null";
}
else if (dtRows.Rows[i][j] + "" == "")
text = "null";
else
{
text = dtRows.Rows[i][j] + "";
// Escape special character for MySQL commands
text = text.Replace("\\", "\\\\");
text = text.Replace("'", "\\'");
text = "'" + text + "'";
}
sb.AppendFormat(text);
if (j + 1 != dtRows.Columns.Count)
sb.AppendFormat(",");
}
if (Construct_SQL_In_One_Line_From_Same_Table)
{
if (i + 1 != dtRows.Rows.Count)
{
sb.AppendFormat("),(");
}
else
{
sb.AppendFormat(");");
}
}
else
{
sb.AppendFormat(");");
SQLs.Add(sb.ToString());
sb = new StringBuilder();
}
}
if (Construct_SQL_In_One_Line_From_Same_Table)
{
SQLs.Add(sb.ToString());
sb = new StringBuilder();
}
}
#endregion
}
string[] output = null;
output = new string[SQLs.Count];
//#region Encryption | Encrypt the output SQL text
//if (EncryptBackupFile)
//{
// XCryptEngine xe = new XCryptEngine();
// xe.InitializeEngine(XCryptEngine.AlgorithmType.Rijndael);
// xe.Key = EncryptionKey;
// for (int i = 0; i < SQLs.Count; i++)
// {
// output[i] = xe.Encrypt(SQLs[i]);
// }
//}
//else
//{
for (int i = 0; i < SQLs.Count; i++)
{
output[i] = SQLs[i];
}
//}
//#endregion
File.WriteAllLines(Filename, output, Encoding.UTF8);
}
public void Restore(string filename)
{
Filename = filename;
Restore();
}
public void Restore(string filename, bool Decryption, string EncryptionKEY)
{
Filename = filename;
Restore();
}
public void Restore()
{
string myCon = "";
if (MySQLConnectionString.Length != 0)
myCon = MySQLConnectionString;
else
{
myCon = "server=" + myServer + ";user=" + myUser + ";password=" + myPassword + ";port=" + myPort + ";";
}
MySqlConnection conn = new MySqlConnection(myCon);
conn.Open(); // Test connection
conn.Close();
string[] sqls = File.ReadAllLines(Filename, Encoding.UTF8);
//if (EncryptBackupFile)
//{
// XCryptEngine xe = new XCryptEngine();
// xe.InitializeEngine(XCryptEngine.AlgorithmType.Rijndael);
// xe.Key = EncryptionKey;
// for (int i = 0; i < sqls.Length; i++)
// {
// sqls[i] = xe.Decrypt(sqls[i]);
// }
//}
NewProgressForm();
progressBar1.Maximum = sqls.Length;
progressBar1.Value = 0;
f.Show();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
conn.Open();
// Start Restoring the Database
foreach (string s in sqls)
{
progressBar1.Value += 1;
cmd.CommandText = s;
cmd.ExecuteNonQuery();
}
f.Close();
}
void NewProgressForm()
{
progressBar1 = new ProgressBar();
progressBar1.Location = new System.Drawing.Point(25, 25);
progressBar1.Size = new System.Drawing.Size(150, 20);
f = new Form();
f.Size = new System.Drawing.Size(220, 120);
f.Text = "Progress...";
f.StartPosition = FormStartPosition.CenterScreen;
f.Controls.Add(progressBar1);
f.ShowIcon = false;
}
}
}
Fifth Step:
Write the following code on that windows form which will be the first form of an application when application starts
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Timers;
namespace AutoBackup
{
public partial class DataBackup : Form
{
public string dbservername, dbusername = "versol", dbpassword = "Abcd1234", database, FileExtension = "sql", dbport, dbbackuppath;
public int backupinterval;
public DataBackup()
{
InitializeComponent();
formload();
System.Timers.Timer mytimer = new System.Timers.Timer(backupinterval * 60 * 1000);
mytimer.Enabled = true;
mytimer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
}
private void ButtonSourcePath_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (DialogResult.OK != fbd.ShowDialog())
return;
TextBoxSourcePath.Text = fbd.SelectedPath;
}
public void OnTimedEvent(object source, ElapsedEventArgs e)
{
//Do the stuff you want to be done every hour;
formload();
backupbuttonclick();
}
public void formload()
{
string path = Application.StartupPath + "\\vsconfig.ini";
if (File.Exists(path))
{
StreamReader sr = new StreamReader(path);
dbservername = sr.ReadLine();
database = sr.ReadLine();
dbport = sr.ReadLine();
backupinterval = Convert.ToInt32(sr.ReadLine());
dbbackuppath = sr.ReadLine();
if (dbservername == null && database == null)
{
MessageBox.Show("Configuration file is empty!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
if (database == null)
{
MessageBox.Show("Database name not configured preperly!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
if (dbport == null)
{
MessageBox.Show("Connection port not configured preperly!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
if (backupinterval == 0)
{
MessageBox.Show("Backup timing does not configured preperly!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
if (dbbackuppath == null)
{
MessageBox.Show("Database backup path does not specified!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
}
if (!File.Exists(path))
{
MessageBox.Show("Configuration file not found!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.Close();
}
}
public void backupbuttonclick()
{
string backupFile = "";
string filter = "";
try
{
//Get the Backup Filename and Path
if (FileExtension != "") filter = "*." + FileExtension + "|*." + FileExtension;
backupFile = database;
backupFile += DateTime.Now.ToString(" yyyy-MM-dd-HH-mm-ss");
if (FileExtension.Length != 0) backupFile = backupFile + "." + FileExtension;
string folderpath = dbbackuppath;
//FolderBrowserDialog fbd = new FolderBrowserDialog();
//fbd.Description = "Choose where to save the backup file.\r\n" + backupFile;
//if (DialogResult.OK != fbd.ShowDialog())
// return;
//folderpath = fbd.SelectedPath;
backupFile = (folderpath + "\\").Replace("\\\\", "\\") + backupFile;
// Start Backup Process
MySqlBackupRestore mb = new MySqlBackupRestore(dbservername, dbusername, dbpassword, database, dbport);
mb.Backup(backupFile);
// End of Backup Process
//MessageBox.Show("Backup Successfully.\n\nYour backup file is created at:\r\n" + backupFile, "Backup", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex) // Log any error that occur during the backup process
{
string errorMessage = "Backup fail.\r\n\r\n" + ex.ToString();
MessageBox.Show(errorMessage, "Error");
}
}
private void DataBackup_Load(object sender, EventArgs e)
{
formload();
}
private void ButtonBackup_Click(object sender, EventArgs e)
{
backupbuttonclick();
}
}
}
Sixth Step:
Write the following code on that form which will be the called first when application starts:
DataBackup db = new DataBackup();
db.formload();
db.backupbuttonclick();
Important Note: file will be saved name as bs2014 2014-11-05-17-51-10
bs2014 is database name
2014-11-05 is current date and
17-51-10 is current time when backup file is created
You can change the format of file name in above code.
You are done. Now when you start the application the application will take the database backup automatically.