How to connect to a Database from VB.Net

Saturday, December 29, 2007 @ 10:04 pm by -DS-

Pogramming 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:

VB.NET:
  1. Public Sub jobcategory_insert(ByVal description As String)
  2. Dim cmd As SqlCommand
  3. Dim sql As String
  4. Try
  5. 'Create the dbinterfase object
  6. Dim dbOp As New dbinterfase
  7.  
  8. sql = "jobcategory_insert"
  9. 'Create a new command with the object connection
  10. cmd = New SqlCommand(sql, dbOp.Conn)
  11. cmd.CommandType = CommandType.StoredProcedure
  12. cmd.Parameters.Add(New SqlParameter("@description", description))
  13.  
  14. cmd.ExecuteNonQuery()
  15. 'Close the database when done
  16. dbOp.CloseDatabase()
  17. Catch ex As Exception
  18. Throw New Exception("job:jobcategory_insert " & ex.Message)
  19. End Try
  20. End Sub

CODE:
  1. <connectionstrings>
  2. <remove name="LocalSqlServer"/>
  3. <add name="dbConexion" connectionString="Server=KAISERLAPTOP\SQLEXPRESS;Database=clasificados;Uid=clasific;Pwd=clasific;Trusted_Connection=no"/>
  4. </connectionstrings>

Very simple, clean and elegant. I have an equivalent class for PHP that I will be posting in a few days.