Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database does not exist error

Tags:

c#

sql-server

When I take a database backup I get an error that the database does not exist, but I can attach the database fine and other processes like data insert and update work fine. But when I take a database backup it gives the error below.

I show the error screen shot and the backup button code

string cnstr="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\fees_data.mdf;Integrated Security=True;User Instance=True;"



SqlConnection connect;
        connect = new SqlConnection(cnstr);
        connect.Open();
        if (txtdname.Text == "")
        { dname = "Default.bak"; }
        else
        { dname = txtdname.Text + ".bak"; }
        SqlCommand command;
        command = new SqlCommand(@"backup database fees_data to disk ='c:\DATABackup\" + dname + "'", connect);
        command.ExecuteNonQuery();
        connect.Close();

When I click the backup button I get the error:

"Database 'fees_data' does not exist. Make sure that the name is entered correctly. BACKUP DATABASE is terminating abnormally."

like image 290
Mihir Avatar asked Sep 25 '26 13:09

Mihir


2 Answers

The database name might not be the same as the .mdf file name.

What results do you get when running this query ?

select name from sys.databases;

Use the correct name from there.

like image 143
driis Avatar answered Sep 28 '26 01:09

driis


instead of this code

SqlCommand command;
   command = new SqlCommand(@"backup database fees_data to disk ='c:\DATABackup\" + dname + "'", connect);
   command.ExecuteNonQuery();

use code written below

string fullPath= "";
 string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;
 fullPath= (System.IO.Path.GetDirectoryName(executable));
 AppDomain.CurrentDomain.SetData("DataDirectory", fullPath);
 fullPath=fullPath+"\\fees_data.mdf";

 SqlCommand command;
 command = new SqlCommand(@"backup ['"+fullPath+"'] to disk ='c:\DATABackup\" + dname + "'", connect);
 command.ExecuteNonQuery();
like image 28
Rashid Avatar answered Sep 28 '26 03:09

Rashid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!