C# .NET - restore database

Asked By kiran Kumar
21-Aug-11 12:19 PM
hi,

  i have created one database in sql server 2005, that database was used in an Windows Forms Application which was developed in visual studio 2008. 

 I gave the database name as "example"  and table name as "sample_table" 

 That sample_table -- contains the employee details which i have entered in textboxes of My Form (designed in WFA )


  Now, i want to run this project in another system ( laptop), For that i have published that project and set up in that PC ,

  But how to store the database which i have generated backup from my first PC (example data base -- example.bak )
  I mean , in new system(PC/Laptop), i have installed sql server , but how to create that database and table which i have used in my windows application in my previous system, how to do it????? pls give me the solution for this
  Radhika roy replied to kiran Kumar
21-Aug-11 12:33 PM

Introduction

The following article describes accessing a SQL Server 2005 database backup and restoring it programmatically using C#.NET 2.0 and SMO. This article provides coding samples to perform the task.

SQL Server Management Objects (SMO) is a collection of objects that are designed for programming all aspects of managing Microsoft SQL Server.

The following namespaces can be used to access SQL Server 2005 programmatically:

  • Microsoft.SqlServer.management
  • Microsoft.SqlServer.Management.NotificationServices
  • Microsoft.SqlServer.Management.Smo
  • Microsoft.SqlServer.Management.Smo.Agent
  • Microsoft.SqlServer.Management.Smo.Broker
  • Microsoft.SqlServer.Management.Smo.Mail
  • Microsoft.SqlServer.Management.Smo.RegisteredServers
  • Microsoft.SqlServer.Management.Smo.Wmi
  • Microsoft.SqlServer.Management.Trace

Pre-Requisite

You need to reference the following namespaces before using this code:

  • Microsoft.SqlServer.Management.Smo;
  • Microsoft.SqlServer.Management.Common;

I used these two class to perform the backup and restore operations:

  • Microsoft.SqlServer.Management.Smo.Backup
  • Microsoft.SqlServer.Management.Smo.Restore

For more information, regarding these two class, check MSDN:

  • http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.backup.aspx
  • http://msdn.microsoft.com/en-us/library/microsoft.sqlserver.management.smo.restore.aspx

Backup database

public void BackupDatabase(String databaseName, String userName, 
            String password, String serverName, String destinationPath)
{
    Backup sqlBackup = new Backup();
    
    sqlBackup.Action = BackupActionType.Database;
    sqlBackup.BackupSetDescription = "ArchiveDataBase:" + 
                                     DateTime.Now.ToShortDateString();
    sqlBackup.BackupSetName = "Archive";

    sqlBackup.Database = databaseName;

    BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
    ServerConnection connection = new ServerConnection(serverName, userName, password);
    Server sqlServer = new Server(connection);
    
    Database db = sqlServer.Databases[databaseName];
    
    sqlBackup.Initialize = true;
    sqlBackup.Checksum = true;
    sqlBackup.ContinueAfterError = true;
    
    sqlBackup.Devices.Add(deviceItem);
    sqlBackup.Incremental = false;

    sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
    sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

    sqlBackup.FormatMedia = false;

    sqlBackup.SqlBackup(sqlServer);
}

Restore Database

public void RestoreDatabase(String databaseName, String filePath, 
       String serverName, String userName, String password, 
       String dataFilePath, String logFilePath)
{
    Restore sqlRestore = new Restore();
    
    BackupDeviceItem deviceItem = new BackupDeviceItem(filePath, DeviceType.File);
    sqlRestore.Devices.Add(deviceItem);
    sqlRestore.Database = databaseName;

    ServerConnection connection = new ServerConnection(serverName, userName, password);
    Server sqlServer = new Server(connection);

    Database db = sqlServer.Databases[databaseName];
    sqlRestore.Action = RestoreActionType.Database;
    String dataFileLocation = dataFilePath + databaseName + ".mdf";
    String logFileLocation = logFilePath + databaseName + "_Log.ldf";
    db = sqlServer.Databases[databaseName];
    RelocateFile rf = new RelocateFile(databaseName, dataFileLocation);
    
    sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
    sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName+"_log", logFileLocation));
    sqlRestore.ReplaceDatabase = true;
    sqlRestore.Complete += new ServerMessageEventHandler(sqlRestore_Complete);
    sqlRestore.PercentCompleteNotification = 10;
    sqlRestore.PercentComplete += 
       new PercentCompleteEventHandler(sqlRestore_PercentComplete);
            
    sqlRestore.SqlRestore(sqlServer);
    db = sqlServer.Databases[databaseName];
    db.SetOnline();
    sqlServer.Refresh();
}

The portion of code uses full backup features. If you want, you can perform incremental and differential backup as well.

plz visit these links

http://www.codeproject.com/KB/database/mft_jet_restore.aspx

http://midnightprogrammer.net/post/BackupRestore-SQL-database-using-C.aspx

  Nitish Gupta replied to kiran Kumar
21-Aug-11 01:31 PM
hello kiran,

it's quiet simple if you are using sql server in your new pc..follow these steps..
1 -just open sql serve
2- right click on database..
3-go to task and
4-click on restore database option..and select the path where your database backup is kept..
5-and click ok.


all the tables along wiyh data comes in your sql server..now you just change the connection string in your project ..according to the system...your project will run..
i hope this may help you...
  Riley K replied to kiran Kumar
21-Aug-11 01:35 PM

Here’s the simplest way to do it

  • Build the application
  • Copy the executable (in the Bin directory) and the app.config file to the other machine. The executable and app.config need to be in the same folder
  • Backup the database on your machine and restore it on the other machine
  • Change app.config to point to the restored database
To know how to restore a database check this link

http://msdn.microsoft.com/en-us/library/ms177429.aspx
  Anoop S replied to kiran Kumar
22-Aug-11 12:45 AM
For that you can use setup and Deployment project, from that click Setup Project


then press ok and continue, there will be option to add database and all
  Vickey F replied to kiran Kumar
22-Aug-11 01:31 AM
First take Backup of database from server machine then restore it.

From MSDN-


http://msdn.microsoft.com/en-us/library/ms177429.aspx

follow these steps-

To restore a full database backup

  1. After you connect to the appropriate instance of the Microsoft SQL Server Database Engine, in Object Explorer, click the server name to expand the server tree.

  2. Expand Databases. Depending on the database, either select a user database or expand System Databases, and then select a system database.

  3. Right-click the database, point to Tasks, and then click Restore.

  4. Click Database, which opens the Restore Database dialog box.

  5. On the General page, the name of the restoring database appears in the To database list box. To create a new database, enter its name in the list box.

  6. In the To a point in time text box, either retain the default (Most recent possible) or select a specific date and time by clicking the browse button, which opens the Point in Time Restore dialog box. For more information, see http://msdn.microsoft.com/en-us/library/ms190982.aspx.

  7. To specify the source and location of the backup sets to restore, click one of the following options:

    • From database

      Enter a database name in the list box.

    • From device

      Click the browse button, which opens the Specify Backup dialog box. In the Backup media list box, select one of the listed device types. To select one or more devices for the Backup location list box, click Add.

      After you add the devices you want to the Backup location list box, click OK to return to the General page.

  8. In the Select the backup sets to restore grid, select the backups to restore. This grid displays the backups available for the specified location. By default, a recovery plan is suggested. To override the suggested recovery plan, you can change the selections in the grid. Any backups that depend on a deselected backup are deselected automatically.

    For information about the columns in the Select the backup sets to restore grid, see http://msdn.microsoft.com/en-us/library/ms178513.aspx.

  9. To view or select the advanced options, click Options in the Select a page pane.

  10. In the Restore options panel, you can choose any of the following options, if appropriate for your situation:

    • Overwrite the existing database

    • Preserve the replication settings

    • Prompt before restoring each backup

    • Restrict access to the restored database

    For more information about these options, see http://msdn.microsoft.com/en-us/library/ms188223.aspx.

  11. Optionally, you can restore the database to a new location by specifying a new restore destination for each file in the Restore the database files as grid. For more information about this grid, see http://msdn.microsoft.com/en-us/library/ms188223.aspx.

  12. The Recovery state panel determines the state of the database after the restore operation. The default behavior is:

    • Leave the database ready to use by rolling back the uncommitted transactions. Additional transaction logs cannot be restored. (RESTORE WITH RECOVERY)

      NoteNote

      Choose this option only if you are restoring all of the necessary backups now.

    Alternatively, you can choose either of the following options:

    • Leave the database non-operational, and do not roll back the uncommitted transactions. Additional transaction logs can be restored. (RESTORE WITH NORECOVERY)

    • Leave the database in read-only mode. Undo uncommitted transactions, but save the undo actions in a standby file so that recovery effects can be reverted. (RESTORE WITH STANDBY)

    For descriptions of the options, see http://msdn.microsoft.com/en-us/library/ms188223.aspx.


Hope this will help you.
  Radhika roy replied to kiran Kumar
22-Aug-11 09:44 AM



To restore a database backup to a different server to a new database 

  1. Copy the database backup file to the target machine or share it on the network so that it is accessible from the server.

  2. Open Enterprise Manager and connect to the server to which the backup is to be restored.

  3. Right-click any database and select All Tasks, then select Restore Database to display the Restore Database dialog box shown in Figure 23.

    Figure 23: “Restore from device” dialog box

    Figure 23: “Restore from device” dialog box
  4. Enter the name of the new database that the backup process will create and restore the backup to, in the Restore as database :list box.

  5. Select the From device radio button.

  6. Click the Select Devices... button.

    Figure 24 : Choose Restore Devices dialog box

    Figure 24 : Choose Restore Devices dialog box
  7. In the Choose Restore Devices dialog box, select either the Disk or the Tape radio button.

    In the dialog box in Figure 24, the Tape option is dimmed (unavailable) because the backup device does not have a tape drive configured. For the purposes of this example we will assume that we are restoring the backup from a disk device.

  8. Click the Add button to display the dialog box shown in Figure 25.

    Figure 25: Choose Restore Destination dialog box

    Figure 25: Choose Restore Destination dialog box
  9. Enter the file name of the backup file that is to be restored. If the file exists on a network share, provide the UNC share name in the File name text box.

    Note   It is recommended that the backup be copied to the server and a local path be used to restore the database.

  10. Click the OK button. The Choose Restore Device dialog box, displayed in Figure 24, is now updated with the selected file.

  11. Click the OK button to return to the Restore Database dialog box. The Devices list is now updated with the file selected in the previous step.

  12. Click the Options tab and select appropriate options for the restore operation. The file names of the physical files may be changed at this time. For more information on the fields in this dialog box, see steps 6 and 7 in Restoring a Complete Backup to a New Database on the Same Server.

  13. Click OK in the Restore Database dialog box. This starts the restore process.

    Progress and confirmation dialog boxes are displayed as SQL Server processes and completes the restore of the database.

  14. Click OK in the confirmation dialog box.

This restore operation may also be accomplished through Transact-SQL commands. The command would be similar to the one demonstrated in Restoring a Complete Backup to a New Database on the Same Server. 


Hope this will help you.

Create New Account
help
SQL Server Management Studio SQL Server Microsoft web page "Introducing SQL Server Management Studio" says that the SQL Server Management Studio is by default installed in C: \ Program
Cannot restart SQL Server service SQL Server I recently installed SQL Server 2008 Express Edition with Advanced Tools. This is the version information from SQL Server Management Studio Microsoft SQL Server Management Studio 10.0.1600.22 ((SQL_PreRelease).080709- 1414 ) Microsoft
SQL Server Management Studio don't see local SQL Server 2005 Devel SQL Server SQL Server Management Studio don't see local SQL Server 2005 Developer Edition x64 on Vista
Can't find SQL Server Management Studio after install SQL Server 2 SQL Server I've installed SQL Server 2005 Developer edition and SQL SP2 on a PC running Windows Vista Business SP1
Additonal thoughts, you should be able to connect to SQL Server via SQL Server SQL Server Additonal thoughts, you should be able to connect to SQL Server via SQL Server Management Studio. This will provide you with whether or not SQL Server