user1799026
user1799026

Reputation: 45

How to Verify If the Database Connection is Successfully Established?

The Controller:

Imports System.Data.SqlClient

Private Sub SqlClientPermission(value As Boolean)
        allowBlankPassword = True
    End Sub


    Function CreateCommand() As SqlCommand

        Dim sqlconnectionCommand As New SqlConnection("Data Source=MSSQLSERVER;server=(localdb)\v11.0;User Id=xxxx_user;Password=;Database=ColorTable_database.sdf;Integrated Security=false;")

        sqlconnectionCommand.OpenAsync()
        sqlconnectionCommand.RetrieveStatistics()

        Dim sqlqueryString As String = "SELECT ColorTable.* FROM ColorTable"
        Dim sqlqueryCommand As New SqlCommand(sqlqueryString, sqlconnectionCommand)

        'Printing Out the SQL Result

        Return ViewData("sqlqueryCommand")

    End Function

The Question:

How can I verify the connection to the database, to see if it is successfully established?

I tried it with RetriveStatistics(), yet I am having a blank page (or result) in the web browser.

EDIT: In this example there is no exception to be handled, as said I am having a blank page, and I am looking to be confirmed that the connection to the database is working, before further proceeding.

The Tools Used: Visual Studio 2012, VB .NET 4.5 MVC 4, Microsoft SQL Server Express

Upvotes: 1

Views: 1216

Answers (2)

usr
usr

Reputation: 171178

Your hunch was correct: The connection is probably not established.

You are calling OpenAsync which is, well, async. The process is not complete when it returns! It looks like what you want is to call Open. When that call is done without exception the connection is working. No need to verify.

Upvotes: 0

hometoast
hometoast

Reputation: 11782

You would typically not explicity verify the conneciton, but instead just use it, and handle the exception.

Upvotes: 1

Related Questions