Access VBA - Pass Param to SQL query? - sql

I have created a function in VBA to connect to a web service and retrieve an XML file.
I then wanted to parse the XML and import the captured nodes into the SQL database.
I have managed to connect to the web service and parse the XML file and even show the values in a messagebox, but when i try and store the parameter via a SQL query, it asks me for a parameter value?
Example:
Set BodyStyle = domResponse.SelectSingleNode("/GetVehicles/DataArea/Vehicles/Vehicle/BodyStyle")
MsgBox (BodyStyle.Text)
DoCmd.RunSQL "INSERT INTO vHPI (BodyStyle) BodyStyle.Text"
The messagebox pops up with a value of MOTORCYCLE, but then i get a prompt asking me for a parameter for BodyStyle.Text
I dont understand how the system can show the parameter in a messagebox but say the parameter is empty when i want to insert it into the database?
Please help!
Thanks
Adam.

You can simply do this:
DoCmd.RunSQL "INSERT INTO vHPI (BodyStyle) VALUES ('" & BodyStyle.Text & "')"
Assuming your column is named BodyStyle and the table is vHPI

Right now you have the literal value of "BodyStyle.Text" on your SQL statement. Try it like this...
DoCmd.RunSQL "INSERT INTO vHPI (BodyStyle) " + BodyStyle.Text

Related

Errors appending to a table in Access VBA

I have an Access database with a VBA module that assembles a JSON string in a variable: JsonStr2 that I want to place in a simple table: JSONforAPI with two fields:
ID = Auto number and
JSON = Long String.
The JSON is valid and Jsonstr2 prints in the immediate window on Debug.Print.
When I run the code line:
DoCmd.RunSQL "INSERT INTO JSONforAPI (JSON) VALUES (" & Jsonstr2 & ")"
I get:
Run time error ‘3075’ Malformed GUID in query expression ‘{"order":{"CustomerID":"19"’.”
On clicking Help I get:
This command isn’t available. Your organization’s administrator turned off the service required to use this feature.
I get the same even if I create a Query Def.
I would be very grateful if someone could tell me what is wrong.
Since you are concatenating your value with the remainder of your SQL statement, none of the delimiters or other special characters within the string held by Jsonstr2 will be escaped and therefore you'll end up with all kinds of malformed strings within the SQL statement.
You should instead use parameters to avoid the need to escape the string, e.g.:
With CurrentDb.CreateQueryDef("","insert into jsonforapi (json) values (#json)")
.Parameters("#json") = jsonstr2
.Execute
End With
You could try this:
DoCmd.RunSQL "INSERT INTO JSONforAPI (JSON) VALUES ('" & Jsonstr2 & "')"
This will single quote Jsonstr2.
As you did not quote the string, it is passed as GUID, not a simple string.

SQLite Inserts - How to Insert Any Text while Avoiding Syntax Errors using Parameterized Values

I'm curious to know a proper way to insert text strings into a database regardless of what characters are contained within the string. What I'm getting at is if I have a string for example that contains single quotes or any other character that is reserved as a 'special' SQL character.
The issue specifically that I'm dealing with is that I don't have control over the possible 'Text' that is being inserted into my database as they text is generated by my application.
One example of where my application fails to insert properly is when there's an error message that happens to contain single quotes. Single quotes are used by SQL statements insert text of course and so I can't insert text that also contains single quotes (outside of using ascii value char(##) function). The issue I'm dealing with is that I'm setting the output of my application to a string variable to then be inserted into my database so I can log activity whether that be standard output or catching errors.
How do I simply INSERT what's contained in my string variable while avoiding all of the SQL Special characters?
Do I need to manually account for all of the SQL Special characters and replace them in my string prior to insert? This sounds like a hit or miss and I'm hoping that there's something already built to accommodate this situation.
Sample Pseudo Code to get the point across:
Let's say an error occurred within the app and it needs to be logged. The error string could be:
Error String: "Error in function calculateStats() parameter 'pBoolStatCheck' is Null"
Now I assign to my string variable within my app and build up the SQL Insert string.
var insertString = "Error in function calculateStats() parameter 'pBoolStatCheck' is Null"
INSERT INTO outputLog(outputLogText)
VALUES ('insertString'); --This will Fail
--Fails due to the variable 'insertString' containing single quotes.
INSERT INTO outputLog(outputLogText)
VALUES ('Error in function calculateStats() parameter 'pBoolStatCheck' is Null');
In closing - since I have no control over the text that could be created by my application how do I account for all of the possible characters that could break my insert?
The code my current application encountering this issue is written in Visual Basic. The database I'm working with is SQLite.
The final solution based on answers received by this post:
Public Sub saveOutputLog(pTextOutput, pTextColor, pNumNewLines, plogType, pMethodSub)
Dim strTableName As String = "outputLog"
Dim sqlInsert As String = "INSERT INTO " & strTableName & "(" &
"outputLog, logColor, numNewLines, logType, method" &
") VALUES (#outputLog, #logColor, #numNewLines, #logType, #method);"
Try
'Open the Database
outputLogDBConn.Open()
'Create/Use a command object via the connection object to insert data into the outputLog table
Using cmd = outputLogDBConn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = sqlInsert
cmd.Parameters.AddWithValue("#outputLog", pTextOutput)
cmd.Parameters.AddWithValue("#logColor", pTextColor)
cmd.Parameters.AddWithValue("#numNewLines", pNumNewLines)
cmd.Parameters.AddWithValue("#logType", plogType)
cmd.Parameters.AddWithValue("#method", pMethodSub)
'Execute the command using above Insert and added Parameters.
cmd.ExecuteNonQuery()
End Using 'Using outputLogDBComm
outputLogDBConn.Close()
Catch ex As Exception
outputLogDBConn.Close()
End Try
End Sub
This problem is very similar to the problem of preventing SQL Injection vulnerabilities in your code. Queries are very easy to break, and while yours breaks in a way that is harmless and annoying, these can be taken to levels where certain inputs can completely destroy your database!
One of the best ways to approach this is by using parameterized queries. This approach is pretty simple; you write the query first with 'placeholders' for the parameters you will send. Once you are ready in your program you can then 'bind' those parameters to the placeholders.
It would look something like the following:
Dim command = New SqlCommand("INSERT INTO outputLog(outputLogText) VALUES (#stringToInsert)", connection);
.
.
.
code
.
.
.
command.Parameters.AddWithValue("#stringToInsert", errorMessage)
.
.
.
execute query
In the above you see that #stringToInsert is the placeholder which is only bound at a later time. It doesn't matter what the variable errorMessage contains, since it will not cause the query to function in a way where the input causes it to potentially break.
There are a lot of resources on this:
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.prepare?view=netframework-4.7.2
Database objects like connections not only need to be closed but also disposed. A Using block will ensure this will happen even if there is an error.
The .Add is better than .AddWithValue for a number of reasons. See https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ and http://www.dbdelta.com/addwithvalue-is-evil/
The parameters of .Add are the name of the parameter, the datatype in the database and optionally the size of the field. You will need to check the database for the last 2.
Open the connection at the last minute befor the execute.
If you are using OleDb with Access, you need to make sure the parameters are added in the same order as they appear in the sql statement.
Using cn As New SqlConnection("Your connection string")
Using cmd As New SqlCommand("INSERT INTO outputLog(outputLogText) VALUES (#outputLogText);", cn)
cmd.Parameters.Add("#outputLogText", SqlDbType.VarChar, 100).Value = TextBox1.Text
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using

MS Access VBA issue

I'm making a report in MS Access - what I'm trying to do here is basically APPEND a query to a table that I've already created - I select the first value, change it and update the table. The issue that I'm coming across is - this report will be used by a VB6 application. So the user won't be seeing Access at all.
The thing with my append query is that it needs a USER ID to run (4 digit number). Normally when I run a report in Access I pass the parameters to a form in Access - and I use them to run queries. However, in this case, I need the user to enter a value when appending the query, additionally, when appending a query in VBA it first says "You are about to append a query, are you sure" (or something along those lines), so is there a way to automate that as well, so when I append it nothing happens?
Here is my code for appending and selecting date from the tempTable:
CurrentDb.Execute "DELETE from [tempCompanyMgmt-NOW];"
DoCmd.OpenQuery "qryCompanyMgmt-SUE" - i made this append!
Set rs1 = CurrentDb.OpenRecordset("Select * from [tempCompanyMgmt-NOW]", , dbOpenDynamic)
So as long as I press OK, YES when I get notified of the APPEND process and enter the parameter for USER ID - everything works fine.
Looks like a typo in your markdown, should the 2nd line be:
DoCmd.OpenQuery "qryCompanyMgmt-SUE - i made this append!"
You'll need to remove the reference to the form inside the qryCompanyMgmt-SUE - i made this append! query, and swap it for a parameter name. You can use the Access interface to explicitly add a parameters clause to the query, and then using ADO (or DAO) from VB6, set a parameter value before you open/execute the query.
The "You are about to append a query, are you sure" message is an Access feature (and it can be disabled), so if you want the VB6 application to provide such a warning, then you'll need to create it yourself with a MsgBox.
One option would by putting your append query into the code and filling in the parameter that way.
I don't know your exact scenario, but something like:
If not isValidUserID(me.UserID) Then
msgbox "Please enter a a valid user id"
exit sub
End If
Dim strSQL As String
strSQL = "DELETE * from [tempCompanyMgmt-NOW];"
CurrentDb.Execute strSQL, dbFailOnError
strSQL = "INSERT INTO tempCompanyMgmt-NOW ( FieldName1, FieldName2, FieldName3 ) " & _
"SELECT FieldName1, FieldName2, FieldName3 FROM tempCompanyMgmt WHERE UseriD=" & Me.UserID
CurrentDb.Execute strSQL, dbFailOnError
To validate the user id you could do something like:
If (Len(me.UserID) = 4 And IsNumeric(me.UserID)) Then
or
Public Function isValidUserID(varUserID As Variant) As Boolean
Dim blnRet As Boolean
If Len(varUserID) = 4 And IsNumeric(varUserID) Then
blnRet = True
End If
isValidUserID = blnRet
End Function
To get rid of the MsgBox telling me I'm about to append a query i included this in my module before I open my append query..
DoCmd.SetWarnings False
And I realized once I have the value passed to the form (userID), that value gets passed on as a parameter when my query gets appended. So it's all set. Thanks for all help!

How to use system username directly in MS Access query?

I would like to know if there is a way to get system username and use it directly in an MS Access query. I have made a parameter work within a query from a combo box on a form and I have also acquired system name in Access VBA using ENVIRON ("USERNAME").
Kindly let me know if this is possible.
You need to create a VBA function that returns the username, and then use the function in the query.
Public Function GetUserName() As String
' GetUserName = Environ("USERNAME")
' Better method, see comment by HansUp
GetUserName = CreateObject("WScript.Network").UserName
End Function
and
SELECT foo FROM bar WHERE myUserName = GetUserName();
My solution kept all the work in VB.
I used a variable for the windows login username and then created a SQL string with that variable inserted. Lastly, I updated the query behind the form to use this new SQL string.
The CHR(34) puts quotes around the name as it is now a string inside the SQLSTR and needs to be within a set of quotes.
If you have a complex SQL statement, write it in the QBE using a string for the name and all the other variables, then switch to the SQL view and replace it using a VBA variable as shown below.
MyName = Environ("username")
sqlstr = "SELECT * From Projects WHERE ( ((Projects.LeadEngineer)=" & Chr(34) & MyName & Chr(34) & " AND ActiveYN = True ));"
Forms![Main Form].RecordSource = sqlstr
You can use SYSTEM_USER if the query is being executed in a SQL Server, that will retrieve the user name connected to the database (for that, make sure you are not using fixed user name in your connection string)
Yes - you can use the 'CurrentUser' function in your query. Here I've included it as a field and criteria.
SELECT Field1, Field2, [CurrentUser] AS UserName FROM Table1 WHERE Field1 = [CurrentUser];

Search function in VB.NET

This is my line of code to search the information from the database. I am trying to display the result obtained from the execution of this line. Should I just use a message box or use any object to display it? I do not want to use dataset.
ACommanad.CommandText = "SELECT * FROM Students where StudentID =" & DeleteRecordTextBox.Text & ""
Yes. A message box is perfectly acceptable way to display something to the user.