Create a database connection class in vb.net

vb.net , sql server , access Colombo, Sri Lanka
  • 7 years ago

    Hi all, I am new to vb.net. I was created an inventory control system. It contain may forms with database connection. I want to know, How to create one class file to connect all forms with database, If any one know please help me. Thank You.

  • 7 years ago

    '====================================== 'Save this as a seperate vb file.when u need to access create an instance and access the related method '======================================= Imports System.Collections.Generic Imports System.Text Imports System.Data.SqlClient Imports System.Configuration Imports System.Data Imports System.Windows.Forms

    Namespace CSharpPractise Public Class DAL Private connectionStat As SqlConnection

    	Public Sub New()
    		connectionStat = New SqlConnection()
    	End Sub
    

    '===================================== 'Open the connection Public Sub SQLConnection() Dim connectionToSQL As New SQLConnectionStirng() connectionStat.ConnectionString = connectionToSQL.getCon() If connectionStat.State = ConnectionState.Closed Then connectionStat.Open() End If

    	End Sub
    

    '=========================================

    '================Close the connection====== Public Sub SQLDisCon() If connectionStat.State = ConnectionState.Open Then 'connectionStat.Dispose();

    			connectionStat.Close()
    		End If
    
    	End Sub
    

    '=================Returns a Data Table============ Public Function returnDataTable(strCmd As String) As DataTable

    		SQLConnection()
    		Dim da As New SqlDataAdapter(strCmd, connectionStat)
    		Dim dt As New System.Data.DataTable()
    		da.Fill(dt)
    		SQLDisCon()
    		Return dt
    
    	End Function
    

    '===================================== '=============Execute SQL Command====== Public Function executeSQL(cmdtext As String) As Integer Try SQLConnection() Dim cmd As New SqlCommand(cmdtext, connectionStat) Return cmd.ExecuteNonQuery()

    			SQLDisCon()
    
    		Catch e As Exception
    			Throw e
    		End Try
    	End Function
    

    '===================================== '===========Returns a Dataset============= Public Function returnDataset(query As String) As DataSet SQLConnection() Dim ds As New DataSet() Dim da As New SqlDataAdapter(query, connectionStat) da.Fill(ds) Return ds 'SQLDisConnection(); SQLDisCon() End Function

    End Class
    

    End Namespace

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“If debugging is the process of removing software bugs, then programming must be the process of putting them in.” - Edsger Dijkstra