0

I built a windows form application using c# as a programming language and MySQL as DBMS, I want to add a button for exporting database when user click it. What I created so far is :

MySqlCommand cmd = new MySqlCommand("SELECT * FROM client INTO OUTFILE '"+path+"' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY'\\n' ", con);
MySqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Read();

But the problem is that this code export data only NOT schema of tables. Is there is any way to export database with schema by SQL statement.

hoger qassim
  • 37
  • 1
  • 9
  • That sounds like a MySQL Dump. [Check out this question](https://stackoverflow.com/questions/12311492/backing-up-database-in-mysql-using-c-sharp) The first answer there uses the `MySqlBackup` object which should create a dump (DROP/CREATE statements and INSERT statements with the data as well). – JNevill Apr 03 '18 at 17:57
  • I already check that question but it didn't work for me, do you think there is SQL statement to export schema with data as well? – hoger qassim Apr 03 '18 at 18:02

1 Answers1

0

You can use MySqlBackup.NET

https://github.com/MySqlBackupNET/MySqlBackup.Net

Sample codes:

Backup a MySQL database

using MySql.Data.MySqlClient; 

then the code,

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


Restore a MySQL database

private void Restore()
{
    string constring = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\\backup.sql";
    using (MySqlConnection conn = new MySqlConnection(constring))
    {
        using (MySqlCommand cmd = new MySqlCommand())
        {
            using (MySqlBackup mb = new MySqlBackup(cmd))
            {
                cmd.Connection = conn;
                conn.Open();
                mb.ImportFromFile(file);
                conn.Close();
            }
        }
    }
}
mjb
  • 7,649
  • 8
  • 44
  • 60