

Line 11 ties the Command to the open SqlConnection and line 12 executes the command using the ExecuteNonQuery method.įinally, the connection is closed to save resources. Line 10 specifies what that text is – the SQL query to back up the database that I showed at the start. As it happens, Text is the default so this line isn’t strictly necessary but I thought it useful to highlight that what’s happening here is that the text of a SQL Query is being passed to the Command. If you’ve read my ADO.NET posts, you’ll know that there are three options. Then in lines 8 to 12 a SqlCommand is created and set to CommandType.Text. Private Sub btnHardCoded_Click(sender As Object, e As EventArgs) Handles btnHardCoded.Clickĭim sqlConnectionString As String = "Integrated Security=SSPI Persist Security Info=False Initial Catalog=Locations Data Source=GIGABYTE-PC\SQLEXPRESS" Dim conn As New SqlConnection(sqlConnectionString)Ĭmd.CommandText = "BACKUP DATABASE Locations TO DISK='C:\Temp\location.BAK'"Ī connection to the database is created and opened. Have a look at the following snippet, which I put in a button click event for convenience and testing: When you stop and think about it, this is just another T-SQL query so you should be able to use it in a SqlCommand just as you use queries that fetch data or interact with the database in other ways. sql file in some of the examples in this post, but first I’ll look at an approach that doesn’t need access to such a file. This script will back up that database:Īlthough I’ve used SQL Server Management Studio to create this query, you can of course just type the code into Notepad and save it with a.

I’ve used a very basic script for this demo.

I can’t promise you that they’re the best way but they do seem to work just fine. In the end, I came up with a couple of solutions. I didn’t, but I do like a challenge! So I set to and tried to research and figure out how this could be done. A colleague asked me if I knew how to back up a database from within a VB.NET application.
