2/8/19

VB.NET Database Connectivity Coding Reference part - 1 | Database Connection


In this Tutorial we are going to look how to connect the database in vb.net.

I have 2 files.
1. Database Class File in VB.NET which filename  is Database.vb
2. Form which Database Connection

 Resource File Download 

Database.vb File Code:
Imports System.Data.SqlClient
Public Class Database

'Dim sqlConn As New SqlConnection With {.ConnectionString = "Server=Najathi\SQLEXPRESS;Database=Student;Integrated Security=SSPI"}

    'Dim sqlConn As New SqlConnection("Server=Najathi\SQLEXPRESS;Database=Student;Integrated Security=True")

    Public sqlConn As New SqlConnection("Server=Najathi\SQLEXPRESS;Database=Student;Integrated Security=SSPI")

'If you have MySql or Access or any other database. you can this class
'OleDbConnection instead of SqlConnection

    Public Function hasConn() As Boolean

        Try
            sqlConn.Open()
            Return True

            sqlConn.Close()

        Catch ex As Exception

            MsgBox(ex.Message)
            Return False

        Finally

            If sqlConn.State = ConnectionState.Open Then
                sqlConn.Close()

            End If

        End Try

    End Function

End Class


Database Connection Form Code:



Public Class FormDatabaseConnection

    Dim db As New Database

    Private Sub ButtonConncted_Click(sender As Object, e As EventArgs) Handles ButtonConncted.Click

        If db.sqlConn.State = ConnectionState.Closed Then

            db.sqlConn.Open()
            LabelDisplay.Text = "connected!"
            LabelDisplay.ForeColor = Color.Green

        End If


    End Sub

    Private Sub ButtonDisconneted_Click(sender As Object, e As EventArgs) Handles ButtonDisconneted.Click

        If db.sqlConn.State = ConnectionState.Open Then

            db.sqlConn.Close()
            LabelDisplay.Text = "Disconneted!"
            LabelDisplay.ForeColor = Color.Red

        End If

    End Sub

    Private Sub ButtonTestConn_Click(sender As Object, e As EventArgs) Handles ButtonTestConn.Click

        If db.hasConn() Then
            MsgBox("Connection Succeed!")
        End If

    End Sub
End Class


No comments:

Post a Comment

About

Hi, I'm Najathi.
I've started entrepreneurial company, Twin Brothers.Inc.
One is self-funded & the other is venture backed. I also send a weekly. where I share relevent, curated links.

Every Week I Publish a short post on writing, publishing, or content of IT Related

Contact Form

Name

Email *

Message *