2009-08-02 21 views
5

tengo el siguiente módulo y me gustaría probar la conexión. ¿Cómo pruebo si la conexión funciona? ¿puedes ser muy específico con su respuesta:¿cómo puedo probar si estoy conectado a sql DB a través de vb.net?

Imports System.Data.SqlClient 

Module Module1 
    Sub Main() 
     ' Create a new SqlConnectionStringBuilder and 
     ' initialize it with a few name/value pairs: 
     Dim builder As New SqlConnectionStringBuilder(GetConnectionString()) 

     ' The input connection string used the 
     ' Server key, but the new connection string uses 
     ' the well-known Data Source key instead. 
     Console.WriteLine(builder.ConnectionString) 

     ' Pass the SqlConnectionStringBuilder an existing 
     ' connection string, and you can retrieve and 
     ' modify any of the elements. 
     builder.ConnectionString = _ 
      "server=http://sql.example.com;user id=******;" & _ 
      "password=***********;" 
     ' Now that the connection string has been parsed, 
     ' you can work with individual items. 
     Console.WriteLine(builder.Password) 
     builder.Password = "[email protected]" 
     builder.AsynchronousProcessing = True 

     ' You can refer to connection keys using strings, 
     ' as well. When you use this technique (the default 
     ' Item property in Visual Basic, or the indexer in C#) 
     ' you can specify any synonym for the connection string key 
     ' name. 
     builder("Server") = "." 
     builder("Connect Timeout") = 1000 

     ' The Item property is the default for the class, 
     ' and setting the Item property adds the value to the 
     ' dictionary, if necessary. 
     builder.Item("Trusted_Connection") = True 
     Console.WriteLine(builder.ConnectionString) 

     Console.WriteLine("Press Enter to finish.") 
     Console.ReadLine() 
    End Sub 

    Private Function GetConnectionString() As String 
     ' To avoid storing the connection string in your code, 
     ' you can retrieve it from a configuration file. 
     Return "Server=(local);Integrated Security=SSPI;" & _ 
      "Initial Catalog=AdventureWorks" 
    End Function 
End Module 

Respuesta

8

Una vez que tenga la cadena de conexión, puede abrir la conexión mediante Connection.Open(). Usted puede hacer que dentro de un bloque try-catch para detectar los errores que se producen al intentar abrir el código connection.enter aquí

En cualquier momento antes de cerrar la conexión con Connection.Close(), se puede comprobar su estado usando Connection.State . Eso devuelve valores en una enumeración, como ConnectionState.Open.

+0

por lo tanto, el simple hecho de abrir una conexión es verificar que se puede conectar a ella – PsychoData

2

crear un objeto de conexión, y abrirlo

Cuestiones relacionadas