Your Ads Here

Friday, 27 April 2012

MySql Database Backup using C#.NET


It shows how to backup MySql Databases using C#.NET.
keywords: mysql, sql, database, backup, tables, C Sharp, .NET

You have add following Controls
1) SaveFileDialog (sfd)
2) ComboBox (cmbDatabase)
3) TextBox (txtExpImpPath, txtWorkingDirectoryPath)

First load the MySql Database to the comboBox.

 
private void getDatabase()
        {
            //Declaration

            OdbcConnection conOdbc = new OdbcConnection();

            DataTable dt = new DataTable();


            //Connection String

            strMySQL = "";

            strMySQL = "Driver={MySQL ODBC 3.51 Driver};option=0;port=3306;server= localhost;uid=root;password=root";

            myChk = "";

            myChk = strMySQL;


            //Open Odbc Connection

            conOdbc = new OdbcConnection(myChk);

            conOdbc.Close();

            conOdbc.Open();


            selectQuery = "SELECT DISTINCT TABLE_SCHEMA FROM information_schema.TABLES ";

            OdbcDataAdapter odbcAdptr = new OdbcDataAdapter(selectQuery, conOdbc);

            odbcAdptr.Fill(dt);


            dtseCt = 0;

            cmbDatabase.Items.Clear();

            cmbDatabase.Items.Add("---Select---");


            while (dtseCt < dt.Rows.Count)
            {
                cmbDatabase.Items.Add(dt.Rows[dtseCt][0].ToString());

                dtseCt = dtseCt + 1;

            }

            cmbDatabase.SelectedIndex = 0;

        }

Connect the database using...
strMySQL = "";

            strMySQL = "Driver={MySQL ODBC 3.51 Driver};option=0;port=3306;server= localhost;uid=root;password=root";

 Here the Complete code for the Database Backup

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic;
using System.Diagnostics;
using System.IO;
using System.Data.Odbc;


namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        string strMySQL = null;
        string myChk = null;
        string selectQuery = null;

        int dtseCt = 0;


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            getDatabase();
        }

        private void getDatabase()
        {
            //Declaration

            OdbcConnection conOdbc = new OdbcConnection();

            DataTable dt = new DataTable();


            //Connection String

            strMySQL = "";

            strMySQL = "Driver={MySQL ODBC 3.51 Driver};option=0;port=3306;server= localhost;uid=root;password=root";

            myChk = "";

            myChk = strMySQL;


            //Open Odbc Connection

            conOdbc = new OdbcConnection(myChk);

            conOdbc.Close();

            conOdbc.Open();


            selectQuery = "SELECT DISTINCT TABLE_SCHEMA FROM information_schema.TABLES ";

            OdbcDataAdapter odbcAdptr = new OdbcDataAdapter(selectQuery, conOdbc);

            odbcAdptr.Fill(dt);


            dtseCt = 0;

            cmbDatabase.Items.Clear();

            cmbDatabase.Items.Add("---Select---");


            while (dtseCt < dt.Rows.Count)
            {
                cmbDatabase.Items.Add(dt.Rows[dtseCt][0].ToString());

                dtseCt = dtseCt + 1;

            }

            cmbDatabase.SelectedIndex = 0;

        }

        private void gettingPath()
        {
            //Getting MySQL Path

            //Declaration

            OdbcConnection conOdbc = new OdbcConnection();

            DataTable dt = new DataTable();

            int len = 0;

            string tempWorkPath = "";

            try
            {
                //Connection String

                strMySQL = "";

                strMySQL = "Driver={MySQL ODBC 3.51 Driver};option=0;port=3306;server= localhost;uid=root;password=root";

                myChk = strMySQL;


                //Open Odbc Connection

                conOdbc = new OdbcConnection(myChk);

                conOdbc.Close();

                conOdbc.Open();


                selectQuery = "select @@datadir";

                OdbcDataAdapter odbcAdptr = new OdbcDataAdapter(selectQuery, conOdbc);

                odbcAdptr.Fill(dt);


                tempWorkPath = dt.Rows[0][0].ToString();

                len = tempWorkPath.Length  - 5;

                txtWorkingDirectoryPath.Text = tempWorkPath.Substring(0, len) + "bin";



            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                //Getting Path

                gettingPath();


                //Save Dialog Box

                sfd.Filter = "SQL Files |.sql";

                sfd.DefaultExt = ".sql";

                DialogResult = sfd.ShowDialog();


                if (DialogResult == System.Windows.Forms.DialogResult.Cancel)
                {
                    MessageBox.Show("Backup Creation Failed");

                    return;

                }

                txtExpImpPath.Text = sfd.FileName;


                //Getting Drives in System

                string[] drives = Environment.GetLogicalDrives();

                string drive = drives[1] + "Temp.sql";


                //Do Events

                Application.DoEvents();


                //Processing


                Process myProcess = new Process();

                myProcess.StartInfo.FileName = "cmd.exe";

                myProcess.StartInfo.UseShellExecute = false;

                myProcess.StartInfo.WorkingDirectory = txtWorkingDirectoryPath.Text;

                myProcess.StartInfo.RedirectStandardInput = true;

                myProcess.StartInfo.RedirectStandardOutput = true;

                myProcess.Start();

                StreamWriter myStreamWriter = myProcess.StandardInput;

                StreamReader mystreamreader = myProcess.StandardOutput;

                myStreamWriter.WriteLine("mysqldump --routines -u root -proot " + cmbDatabase.Text + " -r " + drive + "");

                myStreamWriter.Close();

                myProcess.WaitForExit();

                myProcess.Close();


                //Copying File from user selected path to System Created Path

                File.Move(drive, txtExpImpPath.Text);


                MessageBox.Show("Backup Created Successfully");

            }
            catch (Exception ex)
            {
                MessageBox.Show("Backup Creation Failed");

            }

        }
    }
}


Name the file to backup


Backup created successfully


Backup file views like this

 Note: If you have any suggestions or new topic, please free to contact us
Email: sivodayatech@dotnetdevelopertool.com

TextBox Control Changes in CSharp .NET


Keywords: TextBox, C#, Csharp, .NET, DOTNET.

Windows Forms text boxes are used to get input from the user or to display text. The TextBox control is generally used for editable text, although it can also be made read-only. Text boxes can display multiple lines, wrap text to the size of the control, and add basic formatting. The TextBox control provides a single format style for text displayed or entered into the control. To display multiple types of formatted text, use the RichTextBox control.

The text displayed by the control is contained in the Text property. By default, you can enter up to 2048 characters in a text box. If you set the MultiLine property to true, you can enter up to 32 KB of text. The Text property can be set at design time with the Properties window, at run time in code, or by user input at run time. The current contents of a text box can be retrieved at run time by reading the Text property.
The code below sets text in the control at run time. The InitializeMyControl procedure will not execute automatically; it must be called.

' c Sharp
private void InitializeMyControl()
{
        // Put some text into the control first.
        TextBox1.Text = "This is a TextBox control.";
}


TextBox Properties
TextAlign
HorizontalAlignment.Left
HorizontalAlignment.Right
HorizontalAlignment.Center
 
You can use this property to align the text within a TextBox to match the layout of text on your form. For example, if your controls are all located on the right side of the form, you can set the TextAlign property to HorizontalAlignment.Right, and the text will be aligned with the right side of the control instead of the default left alignment.

BackColor

The BackColor property does not support transparent colors unless the SupportsTransparentBackColor value of System.Windows.Forms.ControlStyles is set to true.
The BackColor property is an ambient property. An ambient property is a control property that, if not set, is retrieved from the parent control. For example, a Button will have the same BackColor as its parent Form by default. For more information about ambient properties, see the AmbientProperties class or the Control class overview.

BorderStyle
BorderStyle.None
BorderStyle.FixedSingle
 
A BorderStyle that represents the border type of the textbox control. The default is Fixed3D.

CausesValidation

Gets or sets a value indicating whether validation is performed when the TextBox control is set to validate when a postback occurs.

Enabled

Gets or sets a value indicating whether the control can respond to user interaction.
true if the control can respond to user interaction; otherwise, false. The default is true.

Font

Defines a particular format for text, including font face, size, and style attributes. This class cannot be inherited.

ReadOnly

Gets or sets a value indicating whether the contents of the TextBox control can be changed.

MaxLength

Gets or sets the maximum number of characters allowed in the text box.

MultiLine

Gets or sets a value indicating whether this is a multiline textbox control.
Name

Represents a control that can be used to display or edit unformatted text.

PasswordChar

Gets or sets the character used to mask characters of a password in a single-line TextBox control.

RightToLeft
RightToLeft.Yes
RightToLeft.No

Gets or sets a value indicating whether control's elements are aligned to support locales using right-to-left fonts.

ScrollBars
ScrollBars.None
ScrollBars.Horizontal
ScrollBars.Vertical
ScrollBars.Both

Visible
Gets or sets a value indicating whether the control and all its child controls are displayed.