简体   繁体   中英

Restoring a backup using SQLCommand in VB.NET

I've got a VB.NET console application I'm creating that will make it easier for people to work with some test databases, and part of this is having a function that restores the database. I thought it was fairly straightforward, and here is the code I have so far:

Sub Restore()
    con = New SqlConnection("Data Source=" & utilnamespace.sqlSvr & ";Database=Master;integrated security=SSPI;")
    cmd = New SqlCommand("ALTER DATABASE [db] SET OFFLINE WITH ROLLBACK IMMEDIATE RESTORE DATABASE db FROM DISK = 'G:\db.bak' WITH REPLACE, STATS = 10", con)
    cmd.Connection.Open()
    cmd.ExecuteNonQuery()
    Console.WriteLine(cmd.CommandText)
    cmd.Connection.Close()

End Sub

The SQL works fine if I run it in SSMS, however it will time out if I try to run it from the app. The problem is that I've read over this and I'm still unsure of what to do.

Should I use BeginExecuteNonQuery and then have it listen for the statement complete message somehow?

Even if I believe that showing a waiting form and waiting for some kind of confirmation would be better for the end user... have you tried changing the timeout in the connection string to solve it in a quick way?

eg (seconds):

string connStr = "Data Source=(local);Initial Catalog=db;
       Integrated Security=SSPI;Connection Timeout=30";

Also check these links:

  1. SQL Server Management Objects (SMO)
  2. SQL Server 2008 - Backup and Restore Databases using SMO

If the database is too big you can increase the timeout of the Command, not the connection string

cmd.Connection.Open()
cmd.CommandTimeout = 100
cmd.ExecuteNonQuery()
Console.WriteLine(cmd.CommandText)
cmd.Connection.Close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM