Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i test if i am connected to sql DB through vb.net?

Tags:

sql

vb.net

i have the following module and i would like to test connection. how do i test if the connection works? can you please be very specific with your answer:

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 = "new@1Password"
        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
like image 943
Alex Gordon Avatar asked Aug 02 '09 19:08

Alex Gordon


1 Answers

After you have the connection string, you can open the connection using Connection.Open(). You can do that within a try-catch block to catch any errors that occur when you attempt to open the connection.enter code here

At any point before you close the connection with Connection.Close(), you can check its state using Connection.State. That returns values in an enum, such as ConnectionState.Open.

like image 163
DOK Avatar answered Sep 26 '22 20:09

DOK