BACKING UP A DATABASE April 2011 Level: By : Feri Djuandi Beginner Intermediate Expert Platform : MS SQL Server 2008, Visual C# 2010 Pre requisites: Suggested to read the first part of this document series titled Connecting the SQL Server as the introduction and basic. In this article we are going to learn how to backup a database using SQL Server Management Objects (SMO). Following are the tools used for the program demo: MS SQL Server 2008 Evaluation Edition MS Visual C# 2010 Express There are three types of database backups that commonly performed in the routine database maintenance: full, differential and transaction log backup. This article will not explain the differences and the details of those types, but we will learn how to run the process easily using SMO. Please open the sample program SmoPractice04.zip attached to this document. Please extract the ZIP file into your local computer and open the project file. Try to run the program, and you will find a screen like this. As moving the selection around from one database to another, you will realize that a transaction log backup is not allowed for some databases. That is because the recovery model of the respective database is Simple. As already known, there are three kinds of database recovery model: full, bulk-logged and simple. Each database in the SQL Server instance may have - 1 -
different configurations. To see or change the option, please use the MS SQL Server Management Studio program and select the database followed by opening the Properties menu. The recovery model is set in the Options page as shown in the following picture. The recovery model is chosen based on the purpose and nature of the database. Please read the SQL Server documentation carefully to know the description of these settings and the effects of changing the value. Anyhow, for the sake of this tutorial, it is enough to know that transaction log backup is allowed for full and bulk-logged, and disallowed for the simple one. Don t ask why, please seek the answer by your self. The outcome of a database backup is a backup file, whether written on a disk, tape or other media. A backup file may contain one or several backup sets. For instance on Sunday you do a full backup, and in the week days you do the transaction log backups in the same backup file. The log backup sets will be appended to the original full backup set, so in the file there will be one full backup set and six transaction log backup sets. In the next Sunday, we need to initialize the backup file to empty it and erase the previous backup sets if not, the subsequent backup set will be kept added into the file and it grows rapidly. That s why in the program sample there is an Overwrite Backup Set option to reset the backup file. Of course there are many different strategies to arrange the backup sets whether put in a backup file or spread over multiple files it is really up to the need. As you are ready to backup, simply press the Backup button and a nice progress bar will be sliding to indicate the progress of the backup process. Now stop the program and look into the source code, let us see how the program works. Please be aware, that firstly we need to reference the SMO libraries into the source code. - 2 -
The first line of the Form class contains a constant declaration of the SQL Server instance. This value should be changed according to your SQL Server installation because (local)\sql2k8 is the instance name that specified in my installation. Next is the declaration of the ServerConnection object to specify the connection parameter to the SQL Server; and finally the Server object as the central of the SMO operation. public partial class Form1 : Form private const string INSTANCE_NAME = "(local)\\sql2k8"; private Microsoft.SqlServer.Management.Common.ServerConnection conn = new ServerConnection(INSTANCE_NAME); private Microsoft.SqlServer.Management.Smo.Server server; public Form1() InitializeComponent(); private void Form1_Load(object sender, EventArgs e) try //Login using Windows Authentication conn.loginsecure = true; conn.connect(); server = new Server(conn); As the program is executed, it immediately tries to connect the SQL Server using Windows authentication. This is done by setting the LoginSecure to True, followed by calling the Connect method. Another alternative to connect is to do it using the SQL Server authentication. If you wish to have more explanation on various methods to connect the SQL Server, please read the first article as suggested earlier. The most important part of the program is in the click event of the Backup button. In this script, the Backup object is created and prepared for the device type (in this example is chosen as File). The backup file path and the backup set name are also specified. string dbname = ""; dbname = lvdatabase.selecteditems[0].text; Microsoft.SqlServer.Management.Smo.Backup backup = new Backup(); Microsoft.SqlServer.Management.Smo.Database database = server.databases[dbname]; backup.database = database.name; backup.devices.adddevice(txtbackupfile.text, DeviceType.File); backup.backupsetname = txtbackupset.text; - 3 -
The rest of the script is quite straight forward. It sets the properties of the Backup object according to the options selected, like backup type, log truncation, backup initialization etc. //The backup type: database, files or log if (rbfull.checked) //Full backup backup.action = BackupActionType.Database; backup.incremental = false; else if (rbdiff.checked) //Differential backup backup.action = BackupActionType.Database; backup.incremental = true; else //Log backup backup.action = BackupActionType.Log; if (cbxtruncatelog.checked) backup.logtruncation = BackupTruncateLogType.Truncate; else backup.logtruncation = BackupTruncateLogType.NoTruncate; //append or overwrite media set if (cbxoverwrite.checked) backup.initialize = true; else backup.initialize = false; Please have a try to perform some database backups in some different scenarios. In my experiment, first I do a full backup then a differential backup and lastly the transaction log backup. All is done in the same backup file, so I expect there are three backup sets inside it. To verify the backup results, we can pretend to about restoring the backup file: - 4 -
1. Open the MS SQL Server Management Studio program and select the Restore Database menu. 2. Select the source as From device, and the backup media as File. Locate the backup file just created and press the Contents button. - 5 -
3. The next window opened shows a header of the backup file. The contents confirm my actions earlier that there are three backup sets representing the full, differential and transaction log backup sets respectively. 4. Press the Close button and cancel the database restore because our intention is only to verify. That s all you need to know how to backup a database in SQL Server using SMO. There are more another interesting and easy-to-learn articles in this SMO series. Please continue reading and enjoy! - 6 -