How to connect to a Database from VB.Net
Saturday, December 29th, 2007
It's been a LONG time since my last programming "tutorial" so let's see how this goes.
When I was a noob (not like I am much of an expert now) I used to write code every time I wanted to connect to a database, as time went on I discovered the advantages of using classes and reusable functions or objects for repeatable tasks, like connecting to a database, and came up with a class named dbinterfase.
When to use it:
On middle to large projects I usually have a class for every table that the application will interact with and its in the methods of those classes that I create the dbinterfase object.
Example:
-
Public Sub jobcategory_insert(ByVal description As String)
-
Dim cmd As SqlCommand
-
Dim sql As String
-
Try
-
'Create the dbinterfase object
-
Dim dbOp As New dbinterfase
-
-
sql = "jobcategory_insert"
-
'Create a new command with the object connection
-
cmd = New SqlCommand(sql, dbOp.Conn)
-
cmd.CommandType = CommandType.StoredProcedure
-
cmd.Parameters.Add(New SqlParameter("@description", description))
-
-
cmd.ExecuteNonQuery()
-
'Close the database when done
-
dbOp.CloseDatabase()
-
Catch ex As Exception
-
Throw New Exception("job:jobcategory_insert " & ex.Message)
-
End Try
-
End Sub
-
<connectionstrings>
-
<remove name="LocalSqlServer"/>
-
<add name="dbConexion" connectionString="Server=KAISERLAPTOP\SQLEXPRESS;Database=clasificados;Uid=clasific;Pwd=clasific;Trusted_Connection=no"/>
-
</connectionstrings>
Very simple, clean and elegant. I have an equivalent class for PHP that I will be posting in a few days.


