共用方式為


How to: Connect to an Instance of SQL Server by Using SQL Server Authentication in Visual Basic .NET

This section describes how to write an SMO application in Visual Basic .NET that connects to a remote instance of SQL Server by using Windows Authentication.

When you connect to an instance of SQL Server by using SQL Server Authentication, you must specify the authentication type. This example demonstrates the alternative method of declaring a ServerConnection object variable, which enables the connection information to be reused.

Connecting to a instance of SQL Server by using SQL Server Authentication

  1. Start Visual Studio 2005.

  2. From the File menu, select New Project. The New Project dialog box appears.

  3. In the Project Types pane, select Visual Basic. In the Templates pane, select Console Application.

  4. (Optional) In the Name box, type the name of the new application.

  5. Click OK to load the Visual Basic console application template.

  6. On the Project menu, select Add Reference item. The Add Reference dialog box appears. Select Browse and locate the SMO assemblies in the C:\Program Files\Microsoft SQL Server\90\SDK\Assemblies folder. Select the following files:

    Microsoft.SqlServer.ConnectionInfo.dll

    Microsoft.SqlServer.Smo.dll

    Microsoft.SqlServer.SqlEnum.dll

    Microsoft.SqlServer.SmoEnum.dll

  7. On the View menu, click Code.-Or-Select the Module1.vb window to display the code window.

  8. In the code, before any declarations, type the following Imports statements to qualify the types in the SMO namespace:

    Imports Microsoft.SqlServer.Management.Smo
    Imports Microsoft.SqlServer.Management.Common
    
  9. Insert the code that follows this procedure into the main program.

  10. Run and build the application.

範例

The example is Visual Basic .NET code that demonstrates how to connect to the remote instance of SQL Server by using SQL Server Authentication.

'Declare a ServerConnection object variable to specify SQL authentication, login and password.
Dim conn As New ServerConnection
conn.LoginSecure = False
conn.Login = vlogin
conn.Password = vpassword
'Connect to the local, default instance of SQL Server.
Dim srv As Server
srv = New Server(conn)
'The actual connection is made when a property is retrieved.
Console.WriteLine(srv.Information.Version)
'The connection is automatically disconnected when the Server variable goes out of scope.

The string variables vLogin and vPassword contain the logon and password.

請參閱

概念

Connecting to an Instance of SQL Server

說明及資訊

取得 SQL Server 2005 協助