Home » .Net, Programming, VB.Net

Simple Data Access Layer

29 April 2010 No Comment

Today we have seen most of the data access layers on the web. Here I have placed some peace of simple Data Access class for your use. This will helpful if you are using quires. This will not useful for stored procedures. You simply form the query and call the ExecuteQuery function.

Class Methods and properties:

ExecuteQueryMode-Enumarator type of Execute Query Mode.

GetConnectionString () – Get the Connection string from the connectionStrings part of the Config file.

CreateConnectionObject () – To create the Connection Object

OpenConnectionObject () – Open the Connection

CloseConnectionObject () Close the Connection

ExecuteQuery () – To execute the given query and return the value (if any)

Implementation:

Inherit the connection class
Just form the Query, whatever you want.
Call the method ExecuteQuery() with the parameter query string and ExecuteQueryMode

'Get Max ProductID
qry = "select Max(ProductID) as MaxID from MProduct"
MaxProdID = ExecuteQuery (qry, ExecuteQueryMode.ReturnSclarValue)

Config file setting:

Data Access Class:

 Public Class Connection

	Dim oleTrans As OleDbTransaction
        Private ConnectionObject As OleDbConnection = Nothing
        Protected strQry As String = String.Empty

        Enum ExecuteQueryMode
            NoReturnValue = 0
            ReturnSclarValue = 1
            ReturnDataRow = 2
            ReturnDataTable = 3
            ReturnDataSet = 4
            ReturnDataReader = 5
        End Enum

        Public Sub CreateConnectionObject()
            ConnectionObject = New OleDbConnection(GetConnectionString)
        End Sub

        Public Function ExecuteQuery(ByVal pSqlQuery As String, ByVal pMode As ExecuteQueryMode) As Object

            Dim lObjReturnValue As Object = Nothing
            Try
                If ConnectionObject Is Nothing Then
                    CreateConnectionObject()
                End If

                OpenConnectionObject()

                Dim oleCommand As New OleDbCommand(pSqlQuery, ConnectionObject)

                If pMode = ExecuteQueryMode.NoReturnValue Then  '' no values return this option.

                    oleCommand.ExecuteNonQuery()
                    CloseConnectionObject()

                ElseIf pMode = ExecuteQueryMode.ReturnSclarValue Then '' This option only return the first column of the first row.

                    lObjReturnValue = oleCommand.ExecuteScalar
                    CloseConnectionObject()

                ElseIf pMode = ExecuteQueryMode.ReturnDataRow Then ''This option returns only first row of the result.

                    Dim dtTable As New DataTable
                    Dim OleDbAdp As New OleDbDataAdapter

                    OleDbAdp.SelectCommand = oleCommand
                    OleDbAdp.Fill(dtTable)

                    If dtTable.Rows.Count > 0 Then
                        lObjReturnValue = dtTable.Rows(0)
                    End If

                    CloseConnectionObject()
                ElseIf pMode = ExecuteQueryMode.ReturnDataTable Then 'this option returns only record set.
                    Dim dtTable As New DataTable
                    Dim OleDbAdp As New OleDbDataAdapter

                    OleDbAdp.SelectCommand = oleCommand
                    OleDbAdp.Fill(dtTable)

                    lObjReturnValue = dtTable

                    CloseConnectionObject()

                ElseIf pMode = ExecuteQueryMode.ReturnDataSet Then ' This option returns mutliple record set.
                    Dim dsDataSet As New DataSet
                    Dim OleDbAdp As New OleDbDataAdapter

                    OleDbAdp.SelectCommand = oleCommand
                    OleDbAdp.Fill(dsDataSet)

                    lObjReturnValue = dsDataSet

                    CloseConnectionObject()
                Else
                    Dim lObjReader As OleDbDataReader
                    lObjReader = oleCommand.ExecuteReader
                    lObjReturnValue = lObjReader
                End If

            Catch ex As Exception
				Throw ex
            End Try
            Return lObjReturnValue
        End Function

        Public Sub OpenConnectionObject()
            If ConnectionObject.State = ConnectionState.Closed Then
				ConnectionObject.Open()
				'oleTrans.Begin()
            End If
        End Sub

        Public Sub CloseConnectionObject()
            If ConnectionObject.State  ConnectionState.Closed Then
                ConnectionObject.Close()
				'oleTrans.Commit()
            End If
        End Sub

        Private Function GetConnectionString() As String
            ' Return "Provider=SQLOLEDB;Data Source=KUMAR;Initial Catalog=MTrans;Integrated Security=SSPI"
            Return Configuration.ConfigurationManager.ConnectionStrings.Item("ConnString").ConnectionString
        End Function

    End Class

Calling Process:

	  Public Class ProductDA
        Inherits Connection

        Dim qry As String = String.Empty

		'''
        ''' Insert Product Details
        '''
        '''
        '''
		Public Sub insertProduct(ByVal ObjBe As ProductBE)
			Dim MaxProdID As Integer = 0
			Try
				Dim StatusID As Int16 = 0
				If ObjBe.StatusID Then StatusID = 1

				' insert into MProduct
				qry = "INSERT INTO MProduct(ProductName,MfrName,Packing,ReOrderLevel,RackNo,UpdatedDate,Status) " & _
				"VALUES('" & ObjBe.ProdName & "','" & ObjBe.MfrName & "','" & ObjBe.Packing & "'," & ObjBe.OrderLevel & ",'" & ObjBe.RackNo & "','" & ObjBe.UpdatedDate & "'," & StatusID & ")"
				' execute query
				ExecuteQuery(qry, ExecuteQueryMode.NoReturnValue)

				'Get Inserted ProductID
				qry = "select Max(ProductID) as MaxID from MProduct"
				MaxProdID = ExecuteQuery(qry, ExecuteQueryMode.ReturnSclarValue)
				ObjBe.ProdId = MaxProdID

				'Insert into TproductSupplier
				For Each Item As Integer In ObjBe.SupplierIds
					ObjBe.SupplierId = Item
					qry = "Insert Into TproductSupplier(ProductID,SupplierID) values(" & ObjBe.ProdId & "," & ObjBe.SupplierId & ")"
					'execute query and return the result
					ExecuteQuery(qry, ExecuteQueryMode.NoReturnValue)
				Next

			Catch ex As Exception
				Throw ex
			End Try
		End Sub
   End Class

I think this will help full for you.If any comments revert back to me.
My email : manivannan.shan@gmail.com

Line Break

Author: Manivannan (6 Articles)

Manivannan

Manivannan obtained Masters in Computer Applications from Periar University, Salem. Presently, working as a Software Engineer in GeoEdge Technologies, Coimbatore. My primary role includes developing applications in Windows and Web using .Net, SQL Server.

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

Spam protection by WP Captcha-Free

Get Adobe Flash playerPlugin by wpburn.com wordpress themes