0

How to restore a database from a .mdf?

I wrote a .mdf to .bak method and the code worked correctly but when I wrote a restore method it did not work.

My code:

private void restoreButton_Click(object sender, EventArgs e)
{
    try
    {
        OpenFileDialog op = new OpenFileDialog();
        op.Filter = "نسخة احتياطية من قاعدة البيانات|*.bak";
        op.Title = "اختر مكان النسخة الاحتياطية";
        // op.FileName = DateTime.Now.ToString("[yyyy-dd-M]-[HH-mm-ss]" + "  " + "  " + "نسخة بتاريخ");

        if (op.ShowDialog() == DialogResult.OK)
        {
            using (SqlConnection Sql_Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString))
            {
                string file = string.Format("backup database [" + System.Windows.Forms.Application.StartupPath + "\\Car_Database] to disk='{0}'", op.FileName);
                string constring = "server=localhost;port3306;user=root;pwd=root;Car_Database=sms; Convert zero Datatime=true;";
                using (MySqlConnection conn = new MySqlConnection(constring))
                {
                    using (MySqlCommand cmd = new MySqlCommand())
                    {
                        using (MySqlBackup mbak = new MySqlBackup(cmd))
                        {
                            cmd.Connection = conn;
                            Sql_Conn.Open();
                            mbak.ImportFromFile(file);
                            Sql_Conn.Close();

                            MessageBox.Show("تمت عملة النسخ بنجاح");
                        }
                    }
                }
            }
        }
    }
    catch (Exception)
    {
        MessageBox.Show("عذراً . لقد حدث خطأ ما اثناء قيامك بعمل نسخة من قاعدة البيانات , الرجاء المحاولة مرة اخرة");
    }
}
Ashen_Boy
  • 15
  • 3
  • What exception message do you get? – DeanOC Aug 13 '22 at 21:40
  • 2
    SqlConnection is for Microsoft SQL Server, MySqlConnection is for Oracle's MySQL (and perhaps MariaDB), you can't just backup and restore between them. – Martheen Aug 13 '22 at 21:47
  • what the Slove???? – Ashen_Boy Aug 13 '22 at 22:00
  • 1
    Are you sure you know which database product you are using? You appear to be confused between SQL Server and MySQL – Charlieface Aug 13 '22 at 22:18
  • Does this answer your question? [How to export SQL Server database to MySQL?](https://stackoverflow.com/questions/3917081/how-to-export-sql-server-database-to-mysql) – Martheen Aug 13 '22 at 22:53
  • **An `.mdf` file is not a backup** - it's a _live_ database file (though probably in a detached state). You can certianly try to attach it but you also need the `.ldf` file too (the `.ldf` is the Transaction Log file, the `.mdf` is everything else). SQL Server backups typically have a `.bak` extension and you can mount them to look-inside. – Dai Aug 14 '22 at 04:36
  • i'm using local sql database – Ashen_Boy Aug 14 '22 at 11:54

0 Answers0