Click here to Skip to main content
15,352,321 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
when i am trying to restore database it gives a error-
SQL
User does not have permission to alter database 'C:\Temp\DB_Jaggry.bak', or the database does not exist.
ALTER DATABASE statement failed.


Code for Restore database-
C#
void Restore(string backUpPath)
        {
            SqlConnection con = new SqlConnection(@"Data Source=SNEHA-PC\SQLEXPRESS;Initial Catalog=DB_Jaggry;Integrated Security=True");
            
                con.Open();
                string DatabaseFullPath = @"C:\Temp\DB_Jaggry.bak";
                string UseMaster = "USE master";
                SqlCommand UseMasterCommand = new SqlCommand(UseMaster, con);
                UseMasterCommand.ExecuteNonQuery();

                string Alter1 = @"ALTER DATABASE [" + DatabaseFullPath + "] SET Single_User WITH Rollback Immediate";
                SqlCommand Alter1Cmd = new SqlCommand(Alter1, con);
                Alter1Cmd.ExecuteNonQuery();

                string Restore = @"RESTORE DATABASE [" + DatabaseFullPath + "] FROM DISK = N'" + backUpPath + @"' WITH  FILE = 1,  NOUNLOAD,  STATS = 10";
                SqlCommand RestoreCmd = new SqlCommand(Restore, con);
                RestoreCmd.ExecuteNonQuery();

                string Alter2 = @"ALTER DATABASE [" + DatabaseFullPath + "] SET Multi_User";
                SqlCommand Alter2Cmd = new SqlCommand(Alter2, con);
                Alter2Cmd.ExecuteNonQuery();
                MessageBox.Show("Restore data succesfully");
                           
        }

when i am changed the Databasefullpath to "DB_Jaggry" it does not give a error but when i check the database i can't restore the database of backUpPath
Plz help me !
Posted
Updated 17-Sep-12 19:31pm
v3

1 solution

Use the following line:
C#
SqlConnection con = new SqlConnection(@"Data Source=SNEHA-PC\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");

You cannot connect to a database which does not exist, connect to the master database first then restore the DB.
   
Comments
NABIN SEN 18-Sep-12 1:07am
   
How to connect to the master database?
Mehdi Gholam 18-Sep-12 1:08am
   
It's in the connection string if you look.
NABIN SEN 18-Sep-12 1:11am
   
it is-Data Source=SNEHA-PC\SQLEXPRESS;Initial Catalog=DB_Jaggry;Integrated Security=True
Prasad_Kulkarni 18-Sep-12 1:32am
   
5'ed :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900