Click here to Skip to main content
16,020,626 members

Comments by Mac McCall (Top 2 by date)

Mac McCall 6-Nov-21 15:23pm View    
Here is a VB class that will let you build parameters and use them in your queries. To use this class, copy it into your project then create a new instance like this:
sqlControl = New SQL Control
There is a default connection string or you can use the override to create you own.

Now when you need to create a SQL statement, create parameters like this:
sqlControl.AddParam("@name", data)
Do this for each data item you need to send to the database.

Finally create and execute you SQL statement like this:
sqlControl.ExecQuery("Select Name from Names where Name = @name"
This returns a datatable called sqlControl.DBDT that will contain the results of your query.

PS: this class can be easily translated to C# if needed.

* Not my code. I found it on YouTube. It's lightweight and fast.

Imports System.Text
Imports System.Data.SqlClient
Imports System.Diagnostics.Eventing.Reader

Public Class SQLControl
Private DBCon As New SqlConnection("server=localhost\SQLEXPRESS;database=HomeDepot;Trusted_Connection=True; ")

'Private DBCon As New SqlConnection("server=localhost\SQLEXPRESS;database=database2;User=database2;Pwd=Password")
Private DBCmd As SqlCommand
Private HasRecords As Boolean = False

' DB Data
Public DBDA As SqlDataAdapter
Public DBDT As DataTable

' Query Parameters
Public Params As New List(Of SqlParameter)

' Query Statistics
Public RecordCount As Int32
Public Exception As String

Public Sub New()

End Sub

' Allow connection string override
Public Sub New(ConnectionString As String)
DBCon = New SqlConnection(ConnectionString)
End Sub

' Execute Query Sub
Public Sub execQuery(Query As String)
' Reset Query Stats
RecordCount = 0
Exception = ""

Try
DBCon.Open()

' Creat DB Command
DBCmd = New SqlCommand(Query, DBCon)

' Load Params into DB Command
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))

' Clear Param List
Params.Clear()

' Execute command and fill datatable
DBDT = New DataTable
DBDA = New SqlDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DBDT)
DBCon.Close()
Catch ex As Exception
' Capture Error
Exception = "ExecQuery Error: " & vbNewLine & ex.Message

Finally
' Close connection
If DBCon.State = ConnectionState.Open Then
DBCon.Close()
End If
End Try
End Sub

' Add Params
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New SqlParameter(Name, Value)
Params.Add(NewParam)
End Sub

Public Function HasException(Optional Report As Boolean = False) As Boolean
If String.IsNullOrEmpty(Exception) Then Return False
If Report = True Then MsgBox(Exception, MsgBoxStyle.Critical, "Exception:")
Return True
End Function

End Class
Mac McCall 5-Nov-21 19:45pm View    
A**hole!