2009-08-02 101 views
5

我有以下模塊,我想測試連接。我如何測試連接是否工作?可以請你非常具體與您的答案:我如何測試如果我通過vb.net連接到sql數據庫?

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 

回答

8

後,您必須在連接字符串,您可以打開使用Connection.Open()連接。 你可以做一個try-catch塊內捕捉出現的任何錯誤,當您試圖關閉與Connection.Close()連接之前打開這裏

的connection.enter代碼在任何時候,你可以檢查使用Connection.State其狀態。這返回枚舉中的值,如ConnectionState.Open

+0

因此,僅僅打開一個連接的行爲就是驗證你可以連接到它 – PsychoData 2014-04-07 14:20:57

2

創建一個連接對象,然後打開它

相關問題