Windows service to take backup of MySQL database at every interval
Hello Coders,
Here in this article i am going to explain you that how you can take a backup of your MySQL database without taking backup from MySQL Workbench. I will create on Windows service to take database backup and it will take backup at regular interval defined in the configuration file. I have defined the interval time in the file, So the user can change the interval timing based on their requirement.
Step 1: Create console application
Step 2: Create two class files
File name: Program.cs, MySQLBackupInstaller.cs
Step 3: Add reference of MySql dll file
Click here to download MySql dll file
Step 4: Add other references in project
1. System.Configuration.Install
2. System.ServiceProcess
Step 5: Write the below code in Program.cs file
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.IO;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Timers;
using System.Runtime.InteropServices;
using System.Security;
using System.ServiceProcess;
namespace MySQLBackup
{
class Program : ServiceBase
{
public string dbservername, dbusername = "nirav", dbpassword = "Pass@1234", database, FileExtension = "sql", dbport, dbbackuppath;
public int backupinterval;
private static System.Timers.Timer mytimer;
public void getdatafromfile()
{
string path = @"C:\vsconfig.ini";
DateTime todate = DateTime.Today.Date;
// below code is for financial year where i am changing the database name. You can hardcode your database name in database variable.
if (todate.Month > 3)
{
database = "BS" + todate.Year;
}
else
{
database = "BS" + todate.AddYears(-1).Year;
}
if (File.Exists(path))
{
StreamReader sr = new StreamReader(path);
dbservername = sr.ReadLine();
dbport = sr.ReadLine();
backupinterval = Convert.ToInt32(sr.ReadLine());
dbbackuppath = sr.ReadLine();
if (dbservername == null || database == null || dbport == null || backupinterval == 0 || dbbackuppath == null)
{
this.Stop();
}
}
else
{
this.Stop();
}
}
public void OnTimedEvent(object source, ElapsedEventArgs e)
{
//taking backup of database
string backupFile = "";
string filter = "";
try
{
#region 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;
backupFile = (folderpath + "\\").Replace("\\\\", "\\") + backupFile;
#endregion
// Start Backup Process
MySqlBackupRestore mb = new MySqlBackupRestore(dbservername, dbusername, dbpassword, database, dbport);
mb.Backup(backupFile);
// End of Backup Process
}
catch (Exception ex) // Log any error that occur during the backup process
{
}
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
getdatafromfile();
mytimer = new System.Timers.Timer();
mytimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
mytimer.Interval = (backupinterval * 60 * 1000);
mytimer.Enabled = true;
}
protected override void OnStop()
{
base.OnStop();
dbservername = null;
database = null;
dbport = null;
dbbackuppath = null;
backupinterval = 5000;
}
static void Main(string[] args)
{
ServiceBase.Run(new Program());
}
public Program()
{
this.ServiceName = "MySQLBackup";
}
}
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 = "";
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 + ";";
//}
myCon = "server=" + myServer + ";user=" + myUser + ";password=" + myPassword + ";Persist Security Info=True;database=" + myDatabase + ";port=" + myPort + ";";
MySqlConnection conn = new MySqlConnection(myCon);
#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];
for (int i = 0; i < SQLs.Count; i++)
{
output[i] = SQLs[i];
}
File.WriteAllLines(Filename, output, Encoding.UTF8);
}
}
}
Step 6: Write the below code in MySQLBackupInstaller.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
namespace MySQLBackup
{
[RunInstaller(true)]
public class MySQLBackupInstaller : Installer
{
string strServiceName = "MySQLBackup";
public MySQLBackupInstaller()
{
var processInstaller = new ServiceProcessInstaller();
var serviceInstaller = new ServiceInstaller();
//set the privileges
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.DisplayName = strServiceName;
serviceInstaller.StartType = ServiceStartMode.Automatic;
//must be the same as what was set in Program's constructor
serviceInstaller.ServiceName = strServiceName;
this.Installers.Add(processInstaller);
this.Installers.Add(serviceInstaller);
this.AfterInstall += new InstallEventHandler(MySQLBackupInstaller_AfterInstall);
}
public void MySQLBackupInstaller_AfterInstall(object sender, InstallEventArgs e)
{
var controller = new ServiceController(strServiceName);
controller.Start();
}
}
}
Step 7: Create one .ini file named vsconfig.ini in root of C drive
See step 5 i have defined the string path = @"C:\vsconfig.ini"; in getdatafromfile function().. You can change it as per your need.
write the below lines in vsconfig.ini file:
127.0.0.1 // server name or ip where the MySql is installed
3306 // port no on which port MySql is running
1 // backup time interval for e.g. 1 means 1 minute
D:\MySQLBackupData // backup path where the backup file will be saved
If the above four lines is not included in the config file than service will not work.
Step 8:Build your project
Step 9: Run .NET Developer Command Prompt or Developer Command Prompt for VS2012 as administrator
Step 10: Go to your path of exe by using cd command. For ex. cd Project (Project is folder name)
Step 11: Write below command to install windows service
installutil MySQLBackup.exe
You are done. Check your database backup path after every interval file.
File will be created as name : BS2015 2015-05-23-12-50-54
BS2015 is the name of your database.
2015-05-23 is the date when your backup file is created.
12-50-54 -->> HH:MM:SS -->> is the time when your backup file is created.