ADO.NET Connection object in VB.NET

Here we see how to use ado.net to connect to a database with the open and close method of SqlConnection class.
  • 4639
 

Connection object

The connection object is used to open a connection to your database (data source). The SqlConnection instance takes Connection String as argument and pass the value to the Constructor statement. The Open() method in SqlConnection class is used to open the Database Connection and The Close() method in SqlConnection class is used to close the Database Connection.

Creating a SqlConnection Object

To create a connection object we pass the connection string.

Dim str As String = "Data Source=.;uid=sa;pwd=123;database=master"

Dim con As New SqlConnection(str)

 

Open() method

 

The open method in SqlConnection class is used to open the Database Connection.

con.open()

 

Close() method

 

The close method is SqlConnection class is used to close the Database Connection.

con.close()

For example

The below example define the connection object with SQL Server database.

 

Imports System.Data.SqlClient

Module Module1

    Sub Main()

        Dim str As String = "Data Source=.;uid=sa;pwd=123;database=master"

        Dim con As New SqlConnection(str)

        Try

            con.Open()

            Console.WriteLine("connection open")

            con.Close()

        Catch ex As Exception

            Console.WriteLine("can not open connection")

        End Try

    End Sub

End Module

OUTPUT

con1.gif

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.