visual studio 2013 - Restore database in SQL LocalDB using VB.NET -
i have project developed in vb.net , sql server 2012 localdb (v11) , need backup/restore facility in application. backup part complete stuck @ restore part. query want worked (and working fine in sql editor)
alter database [<.mdf file path>] set single_user rollback immediate restore database [<.mdf file path] disk='<.bak file path'
and here code in vb.net trying execute
sub restorequery(byval que string) mainform.conn.close() con = new sqlconnection("data source=(localdb)\v11.0;database=master;integrated security=true;") if not con.state = connectionstate.open con.open() cmd = new sqlcommand(que, con) cmd.executenonquery() end sub
and here approaches tried far
using same query above
restorequery("alter database [<.mdf file path>] set single_user rollback immediate") restorequery("restore database [<.mdf file path>] disk='<.bak file path>'")
and results in error
exclusive access not obtained because database in use. restore database terminating abnormally.
after finding reason above issue (which nonsense after using
master
database while opening connection , closing opened connections usingmainform.conn.close()
), tried second approach per links , references stackoverflow. , here queries tried:restorequery("use [master] ") restorequery("alter database [<.mdf file name>] set single_user rollback immediate") restorequery("restore database[<.mdf file name>] disk='<.bak file name>'") restorequery("alter database [<.mdf file name>] set multi_user") restorequery("use [<.mdf file name>]")
and here error got while executing second query :
additional information: user not have permission alter database <.mdf file name path>, database not exist, or database not in state allows access checks. alter database statement failed.
is there other way restore sql server localdb using vb.net ?
i have used code in 1 of project.
try openfiledialog1 .filter = ("db backup file|*.bak;") .filterindex = 4 end openfiledialog1.filename = "" if openfiledialog1.showdialog() = dialogresult.ok cursor = cursors.waitcursor sqlconnection.clearallpools() con = new sqlconnection(cs) con.open() dim cb string = "use master alter database [" & system.windows.forms.application.startuppath & "\brh.mdf] set single_user rollback immediate restore database [" & system.windows.forms.application.startuppath & "\brh.mdf] disk='" & openfiledialog1.filename & "' replace alter database [" & system.windows.forms.application.startuppath & "\brh.mdf] set multi_user " cmd = new sqlcommand(cb) cmd.connection = con cmd.executereader() con.close() end if catch ex exception messagebox.show(ex.message, "error", messageboxbuttons.ok, messageboxicon.error) end try
Comments
Post a Comment