简体   繁体   中英

how to use VB.NET to connect to sql server with user 'sa' and restore a database

I am new to VB.NET, and needed some help to make a connection to sql server.

I instralled sql server 2008 r2 express with instance name "sqlexpress", and passowrd "sql123".

I need to create a connection to this server instance, with user 'sa', and restore my .bak database file. After this I thought to create a new user with name and password 'inituser', only for this database, running a T-SQL query with VB.NET.

This is my initial function:

Private Sub DBConnect()
    Dim myConn As SqlConnection
    Dim q1 As SqlCommand
    Dim q2 As SqlCommand

    myConn = New SqlConnection(@"Server=.\SQLEXPRESS;User Id=sa;Password=sqlexpress1;")
    ' restore the databse .bak file
    q1 = myConn.CreateCommand
    q1.CommandText = "RESTORE DATABASE AdventureWorks2012 FROM DISK = '" + _DBFilePath + "'"
    ' create new user for EasyFarmacy Database
    q2 = myConn.CreateCommand
    q2.CommandText = "CREATE LOGIN inituser WITH PASSWORD = 'inituser' USE EasyFarmacy GO CREATE USER inituser FROM login inituser GO"

    Try
        myConn.Open()
        q1.ExecuteNonQuery()
        q2.ExecuteNonQuery()
    Catch ex As Exception
        MsgBox("Database connection error!  + '" + ex.Message + "'")
    End Try
    myConn.Close()
End Sub

Can anyone help me?

Of course a command like that needs to be executed with ExecuteNonQuery

myCmd.CommandText = "CREATE LOGIN inituser WITH PASSWORD = 'inituser'"
myConn.Open()
myCmd.ExecuteNonQuery

Now, for the Restore part I suggest to use a reference to the SMO Libraries deployed with your installation of Sql Server. You could find the assemblies required in GAC

Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.Management.Sdk.Sfc
Microsoft.SqlServer.Smo
Microsoft.SqlServer.SmoExtended

and then you could use the Restore class to perform your operation. The steps required are numerous and they depend on your context. So I give your a link to the MSDN page about this Restore class where you could find a full example of a restore operation executed programmatically

you gave to execute your command:

Private Sub DBConnect()
Dim myConn As SqlConnection
Dim myCmd As SqlCommand

myConn = New SqlConnection(@"Server=.\SQLEXPRESS;User Id=sa;Password=sql123;")
myCmd = myConn.CreateCommand
myCmd.CommandText = "CREATE LOGIN inituser WITH PASSWORD = 'inituser'"
myConn.Open()
myCmd.ExecuteNonQuery()



myConn.Close()

End Sub

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