tags:

views:

47

answers:

4

i have a windows application, the database is sql express how can i backup and restore the database using my application

+1  A: 

You could have your application launch a .sql file that does the backing up or restoring for you. Granted, I've mostly seen this done in a Scheduled Task, but I suppose you could do it from a triggered event inside your app.

System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo.FileName = "C:\\path\\to\\backup.sql";
p.Start();

UPDATE:

As pointed out in the comments, this won't work if you don't have SQL Management Studio installed on the server. Alternatively, you could call a stored procedure. Upon reflecting, I'm not sure why I didn't suggest the stored proc first - probably because the other methodology was fresh on my brain due to being forced to implement it that way in a previous project.

JustLoren
This assumes the Management Studio is installed in the same machine as the windows app. That could not be the case, so this is not going to work always.
iCe
Good point, sir. I'll amend my solution accordingly.
JustLoren
A: 

JustLoren already provided a way to do what you want, but whatever you do, remember to check the completion code! (sorry, not enough rep to comment)

belisarius
A: 

You can request a backup from within your app by executing:

@"BACKUP DATABASE [MyDBName] TO DISK = 'c:\somedir\MyDBName.bak' WITH INIT" (ref)

Or use SQL SMO Objects SqlBackup() directly.

Alex K.
A: 

You could use SQL Server Management Objects

First add a reference in your project to: Microsoft.SqlServer.Smo.dll, Microsoft.SqlServer.SmoExtended.dll, Microsoft.SqlServer.SqlEnum.dll and Microsoft.SqlServer.SmoEnum.dll.

After that to Backup your Database follow this sample:

//Connect to the server
Server srv = new Server();
//If Sql Server is not local or is a named instance you could do 
//Server srv = new Server("SERVERNAME");

Database db = srv.Databases("YourDB");

//Create a backup definition
Backup backup = new Backup(); 

backup.Action = BackupActionType.Database; 
backup.BackupSetDescription = "Full backup of Adventureworks2008R2"; 
backup.BackupSetName = "My app Backup"; 
backup.Database = "YourDB"; 

//Configure the backup device

BackupDeviceItem backupDevice = new BackupDeviceItem("YourDB.bak", DeviceType.File); 

backup.Devices.Add(backupDevice); 

//Specify wether do a full backup or not
backup.Incremental = false; 

//Specify log truncation mode
backup.LogTruncation = BackupTruncateLogType.Truncate; 

//Do the backùp
backup.SqlBackup(srv); 
iCe