I am developing a front-end application for data entry in Access. The database is hosted on SQL Server, and I only use Access to interact with it. All queries are performed through DAO via ODBC connection. However, I have realized that my code is at risk of SQL injection when concatenating values even with the use of @DECLARE. I would like assistance on how to create a parameterized query to avoid SQL injections.
I have read that an alternative is to use ADO, but I am comfortable working with DAO. I would like to know if I can pass parameterized queries with DAO and let SQL Server handle the rest.
I am sharing an example of my code:
In this example, I am using DAO to execute the query directly on the SQL Server engine. If you have concerns about SQL injection, it is advisable to switch to parameterized queries to enhance security.
If you believe that the most effective solution would be to use ADO, I would like you to tell me how and why. Thank you.
I have read that an alternative is to use ADO, but I am comfortable working with DAO. I would like to know if I can pass parameterized queries with DAO and let SQL Server handle the rest.
I am sharing an example of my code:
Code:
' ---------------------------------------------------------------------------------
' FUNCTION InsertUpdateDelete (Passes an strSQL, connects to SQL Server, and executes the query directly on the SQL Server engine)
' ---------------------------------------------------------------------------------
Public Function InsertUpdateDelete(strSQL As String, ReturnsRecords As Boolean, PTQSubform As Variant, WinLabel As Variant, Optional HorasBox As Variant) As Boolean
On Error Resume Next
Dim qdf As QueryDef
' Create a QueryDef
Set qdf = CurrentDb.CreateQueryDef("")
' Connection to SQL Server
qdf.Connect = "ODBC;DSN=SQL Server;Trusted_Connection=Yes;DATABASE=x;"
qdf.SQL = strSQL
qdf.ReturnsRecords = ReturnsRecords ' Use the provided value
' Execute the query
qdf.Execute dbFailOnError
' Close the query and release resources
qdf.Close
Set qdf = Nothing
End Function
Code:
Private Sub event_save_bttn_Click()
If Not ValidateControls(Me.Cb_event_type, Me.cb_event_name) Then
Exit Sub
End If
Dim confirmation As VbMsgBoxResult
confirmation = MsgBox("Confirm that the data is correct. Once saved, you won't be able to delete it.", vbQuestion + vbYesNo, "Addition Confirmation")
If Not confirmation = vbYes Then
Exit Sub
End If
Dim strSQL As String
strSQL = "DECLARE @event_type NVARCHAR(40), @event_name NVARCHAR(40);" & _
"SELECT @event_type = N'" & Me.Cb_event_type.Value & "'; " & _
"SELECT @event_name = N'" & Me.cb_event_name.Value & "'; " & _
"INSERT INTO operations.dim_event (event_type, event_name) " & _
"VALUES (@event_type, @event_name);"
InsertUpdateDelete strSQL, False, Forms!Update_1!SUB_dim_event, event_win
End Sub
If you believe that the most effective solution would be to use ADO, I would like you to tell me how and why. Thank you.