What's wrong with this SQL code? (VBA MS Access) - mysql

insertString = "INSERT INTO paymentRecord(paymentEventDate,paymentType,paymentRecordNotes,value,clientID,jobID)
VALUES (recordDate,recordType,recordNotes,paymentValue,clientID,jobID);"
DoCmd.SetWarnings False
DoCmd.RunSQL insertString
DoCmd.SetWarnings True
This code returns a syntax error and I don't know why. All insert values and columns are correct.
The code is being used in a MS Access front-end with a MySQL database back-end.

You must concatenate the values:
" .. VALUES (" & recordDate & "," & recordType & "," & recordNotes & "," & paymentValue & "," & clientID & "," & jobID)"
Also, the values must be formatted and delimited correctly, for example by using my function CSql.
Even better, use parameters.

Related

SQL code in VB MS Access inserts the new records to the middle of the table, not at the botom

In MS Access, I need to insert new records using SQL code.
I wrote the following code in VB and it inserts the code to the middle of the table.
Is there any chance to find out the reason?
sql = "INSERT INTO Audit_riskModelHistory (Action, User, modelKey, modelEventKey) " & _
"VALUES ('New Record Inserted', 'Mike-Admin', " & _
Me.cmb1.Value & ", " & Me.cmb2.Value & ")"
DoCmd.SetWarnings False
DoCmd.RunSQL (sql)
DoCmd.SetWarnings True
I tried looking at the properties of the table but I did not find the reason.

Running an SQL string in VBA?

Iv created the SQL string sql in ms access vba but when it runs it prints the string in the debug window but doesn't actually run the string to add a record to the table like I want it to.
Public Sub EmpoyeesTable_Click()
Dim sql As String
sql = "INSERT INTO Employees " & _
"VALUES " & "(1, 'James', 'Dan', 'n6 indro Rd', 0943747, 30.24);"
Debug.Print sql
End Sub
Ultimately I want to use SQL strings to take input from a form when submit is clicked and add it to a table? Is this even the right approach?
There are many ways to run SQL strings in VBA. Each have their own advantages, and disadvantages. The most common ones are:
DoCmd.RunSQL sql
Runs the SQL just as it would if you executed a query. Popup will occur when you add, delete or modify records. You can use UDFs and form parameters
DoCmd.SetWarnings False
DoCmd.RunSQL sql
DoCmd.SetWarnings True
Disables warnings, then runs the SQL like in the previous way, then sets warnings back on.
CurrentDb.Execute sql
Executes the SQL over a DAO connection to the current database. You can't use UDFs and form parameters here. No warnings are shown. It just executes the SQL.
CurrentProject.Connection.Execute sql
Executes the SQL over an ADO connection to the current database. Very similar to the DAO connection, but there are subtle differences. For example, you can execute DDL statements that contain the Decimal data type, and set Check constraints in this way, while both are not allowed in any of the other ways.
You can read about using parameters with these different ways here. That's strongly recommended if you are going to insert values that aren't constant, to avoid bugs and SQL injection.
If you think simply then just change your Debug.Print sql to DoCmd.RunSQL (sql)
Private Sub Command0_Click()
Dim sql As String
sql = "INSERT INTO Employees " & _
"VALUES " & "(1, 'James', 'Dan', 'n6 indro Rd', 0943747, 30.24)"
DoCmd.RunSQL (sql)
End Sub
If you want take values from form then refer each value from form control like text box. See the below codes.
Private Sub Command0_Click()
Dim sql As String
sql = "INSERT INTO Employees VALUES (" & _
"'" & Me.Text1 & "'," & _
"'" & Me.Text2 & "'," & _
"'" & Me.Text3 & "'," & _
"'" & Me.Text4 & "'," & _
"'" & Me.Text5 & "'," & _
"'" & Me.Text6 & "');"
DoCmd.RunSQL (sql)
End Sub
If the field value is number type the you can remove singe quote (') from code for those field.

A character is cut off when data from a textfield in a form containing two dots has to be inserted into a table

When I want to insert data from a form into a table in MS Access 2010 using the following code I receive a runtime error '3075'.
It says: Syntax error in the query experession '123.11.1' even though the text field "AbsErst" contained '123.11.11'. When I enter something without dots or with only one dot into "AbsErst" the code runs perfectly and inserts the data into the table.
I looked for other questions with the same error code but did not find the same issue there.
Looking forward for your answers or ideas
Henrik
Private Sub cmdStore_Click()
CurrentDb.Execute "INSERT INTO tblAbschnitt(INST_F,GDE_F,ABT_F,RW_F,Erst,Stand) " & " VALUES(" & _
Me.cboInst & "," & Me.cboGem & "," & Me.cboAbt & "," & Me.cboRW & "," & Me.AbsErst & "," & Me.absStan & ")"
End Sub
If you want to insert text into a table (and '123.11.1' is text), then you have to enclose it with single quotes in the SQL statement.
CurrentDb.Execute "INSERT INTO tblAbschnitt" & _
"(INST_F,GDE_F,ABT_F,RW_F,Erst,Stand) " & _
" VALUES(" & Me.cboInst & _
"," & Me.cboGem & _
"," & Me.cboAbt & _
"," & Me.cboRW & _
",'" & Me.AbsErst & "'" & _
"," & Me.absStan & _
")"
Do this not only with Me.AbsErst but with all text columns. You have to make sure for all those columns that the value to be inserted does not contain any single quotes themselves. They'd need to be escaped by another single quote. (Cue: SQL Injection)
All this could be probably done much easier and safer if you do not use an INSERT statement but something like this:
With CurrentDb.OpenRecordset("tblAbschnitt")
.AddNew
.Fields("INST_F") = Me.cboInst
.Fields("GDE_F") = Me.cboGem
.Fields("ABT_F") = Me.cboAbt
.Fields("RW_F") = Me.cboRW
.Fields("Erst") = Me.AbsErst
.Fields("Stand") = Me.absStan
.Update
End With
This way all the escaping and single quotes are handled automatically.

append query in VBA (run-time error 3067)

I'm pulling seven values from unbound text boxes on a form into variables. Five of the variables are string type, two are double. I'm then using sql to append the data to a table using a where statement and a global variable which contains a foreign key I used from another table, since I was unsure how to use openargs with browseto...
Option Compare Database
Private Sub Form_Load()
Dim rowN, rowR, mat, crew, perCom As String
Dim budEst, curBud As Double
End Sub
Private Sub btnCapSubmit_Click()
rowN = Me.CAP_ROW_N
rowR = Me.CAP_ROW_R
mat = Me.CAP_MAT
crew = Me.CAP_CREW
perCom = Me.CAP_PER
budEst = Me.CAP_BUD_EST
curBud = Me.CAP_BUD_CUR
Dim appendIt As String
appendIt = "INSERT INTO CAPITAL " & _
"([CAPITAL].[CAP_ROW_N], CAPITAL.[CAP_ROW_R], [CAPITAL].[CAP_MAT], [CAPITAL].[CAP_CREW], [CAPITAL].[CAP_PER], [CAPITAL].[CAP_BUD_EST], [CAPITAL].[CAP_BUD_CUR]) " & _
"VALUES ('" & rowN & "','" & rowR & "','" & mat & "','" & crew & "','" & perCom & "','" & budEst & "','" & curBud & "') WHERE [PRO_ID] = '" & gblFind & "';"
Debug.Print appendIt
DoCmd.RunSQL appendIt
DoCmd.BrowseTo acBrowseToForm, "frmSearchEdit", "NavForm.NavigationSubform", , , acFormEdit
End Sub
Access complains with error #3067, "Query input must contain at least one table or query."
I have no idea what I'm doing.
I tried using debug.print but didn't see anything right off the bat. Then again I've been working on this database all day, so I could be overlooking something really easy.
P.S. I also tried replacing the variables with Me.CAP_ROW_N (textbox names), but no dice.
It's unclear what you are trying to do here, but an INSERT INTO ... VALUES () statement does not take a WHERE clause. Error 3067 is "Query input must contain at least one table or query." You are likely seeing this error because you have included a WHERE clause but you are not selecting existing values from a table.
Try this instead:
appendIt = "INSERT INTO CAPITAL " & _
"([CAPITAL].[CAP_ROW_N], CAPITAL.[CAP_ROW_R], [CAPITAL].[CAP_MAT], [CAPITAL].[CAP_CREW], [CAPITAL].[CAP_PER], [CAPITAL].[CAP_BUD_EST], [CAPITAL].[CAP_BUD_CUR]) " & _
"VALUES ('" & rowN & "','" & rowR & "','" & mat & "','" & crew & "','" & perCom & "','" & budEst & "','" & curBud & "');"
There are several other issues here as well. I will just list them and let you Google for more guidance:
You should use the .Execute DAO method instead of DoCmd.RunSQL because it allows for better error handling, especially when used with the dbFailOnError option.
You will eventually run into trouble using single-quotes on unescaped inputs. For example, WHERE LastName = 'O'Malley'
You appear to be treating all seven values as text by wrapping them in quotes, even though you said two of your values were numeric (double). Numeric values do not get quotes.
Do not qualify the field names with the table name in your field list.
A WHERE clause doesn't belong in an INSERT ... VALUES statement; get rid of that.
This is a smaller-scale example of the pattern I think you want:
appendIt = "INSERT INTO CAPITAL " & _
"([CAP_ROW_N], [CAP_ROW_R]) " & _
"VALUES ('" & rowN & "','" & rowR & "');"
However, I suggest you tackle this with a parameter query.
appendIt = "INSERT INTO CAPITAL " & _
"(CAP_ROW_N, CAP_ROW_R) " & _
"VALUES (pCAP_ROW_N, pCAP_ROW_R);"
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, appendIt)
qdf.Parameters("pCAP_ROW_N") = Me.CAP_ROW_N.Value
qdf.Parameters("pCAP_ROW_R") = Me.CAP_ROW_R.Value
qdf.Execute dbFailOnError
Note I used the text box values for the parameter values directly --- instead of declaring variables to hold the text box values.
Also notice one of the benefits of parameter queries is you needn't bother with delimiters for the values: quotes for text; or # for dates.

DoCmd.RunSQL mySql got Run-time error '3464'

I have this simple code of vba access to update product in the database. But when I debug, it stops at the DoCmd statement and got run-time error. I've made research about this kind of error and code, and had changed the code but still caused an error. Below is my simple code to update the product value.
Sub UpdateProduct()
Dim mySql As String
mySql = "UPDATE " & Forms!UPDATE_PRODUCT!cbxLensType _
& " SET LOT_NO = " & Forms!UPDATE_PRODUCT!txtLotNo _
& " WHERE EAN_CODE = " & Forms!UPDATE_PRODUCT!txtEan & ";"
DoCmd.RunSQL mySql
End Sub
Could you help me to explain what is the problem to my code? Is it because of the update syntax?
Thanks in advance.
**New to access vba
Since EAN_CODE is Text type you need to enclose it inside single quotes.
Sub UpdateProduct()
Dim mySql As String
mySql = "UPDATE [" & Forms!UPDATE_PRODUCT!cbxLensType _
& "] SET LOT_NO = " & Forms!UPDATE_PRODUCT!txtLotNo _
& " WHERE EAN_CODE = '" & Forms!UPDATE_PRODUCT!txtEan & "';"
DoCmd.RunSQL mySql
End Sub
If LOT_NO is also a Text type, make sure that it is also enclosed in Single quotes.