[VB.NET] CRUD Class ADO.NET


Description

This article i will show you crud using template class that i create. very simple to use and clean code. here's this class :


Public Class database
    Implements IDisposable

    Public Function runningQuery(ByVal querystring As String) As DataTable
        Dim dbcmd, adaptor, datacontent
        Dim dbconn = New OleDbConnection

        dbconn.ConnectionString = "FILE NAME=" & My.Application.Info.DirectoryPath & "\connectionFile.udl"
        dbcmd = New OleDbCommand(querystring, dbconn)
        dbcmd.CommandType = CommandType.Text
        adaptor = New OleDbDataAdapter(dbcmd)
        datacontent = New DataTable
        adaptor.Fill(datacontent)
        dbconn.Close()
        Return datacontent
    End Function

    Public Sub executeQuery(ByVal querystring As String)
        Dim dbcmd
        Dim dbconn = New OleDbConnection
        dbconn.ConnectionString = "FILE NAME=" & My.Application.Info.DirectoryPath & "\connectionFile.udl"
        dbconn.Open()

        'Execute Query :
        ' INSERT : "insert into table (field1,field2) values ('1','yeah')"
        ' Delete : "update table set field1 ='abc' where  field2 = '1' "
        ' Update : "delete from table where field1 = '1' "

        dbcmd = New OleDbCommand(querystring, dbconn)
        dbcmd.CommandType = CommandType.Text
        dbcmd.ExecuteReader()
        dbconn.Close()
    End Sub
End Class

here's how to use this class :

  1. Add Class and copy paste class code above, give name the class : database
  2. Define and make object from that class :
    Dim objdatabase As New database
  3. now you can use the object, INSERT DELETE and UPDATE use executeQuery() function because it's doesn't return any value. SELECT use runningQuery() function and it's always return type data : dataTable. 
  4. Example runningQuery()
    Dim objdatabase As New database
    Dim employeeData as dataTable

    employeeData = objdatabase.runningQuery("select * from table where field1='xxx' ")
    ' type dataTable functionality :
    - to check count : 
    employeeData.rows.count
    - to get value field :
           - if string type : 
    employeeData .Rows(index).Field(Of String)("FIELD_NAME")
           - if integer type : employeeData .Rows(index).Field(Of Integer)("FIELD_NAME")
  5. After use release the object from memory
       objdatabase.Dispose()
       objdatabase = Nothing
       GC.Collect()

Post a Comment

Harap gunakan bahasa yang baik dan sopan, terima kasih