Run-time error 3134 "Syntax error in INSERT INTO statement" - vba

I am for the first time posting question in this platform. Currently, I am running into a problem of executing my assignment of online shopping database. When I try to register an account into it, it always pops up a window say run-time 3134 error, syntax error in INSERT INTO statement. I was trying any possibilities in order to solve the problem but it won't work. So, any solution to counter this problem? Thanks for your many helping. 😊
Here is my codes:
CurrentDb.Execute "INSERT INTO Login table (FirstName,LastName,Gender,UserName,Password,Email,Phone) VALUES ('" & Me.FirstName & "','" & Me.LastName & "','" & Me.Gender & "','" & Me.UserName & "', '" &
Me.Password & "','" & Me.Email & "','" & Me.Phone & "')"

Presuming that the table you're trying to INSERT INTO is named Login Table, you have a space in the table name, which means any time you reference that table you need to surround it in square brackets.
CurrentDb.Execute "INSERT INTO [Login table]` (FirstName,LastName,Gender,UserName,Password,Email,Phone) VALUES ('" & Me.FirstName & "','" & Me.LastName & "','" & Me.Gender & "','" & Me.UserName & "', '" &
Me.Password & "','" & Me.Email & "','" & Me.Phone & "')"
This is one of the main problems with naming your table with spaces. Also, Login table is an especially bad name - you already know it's a table, so why do you need to repeat that information in the table name? And if you insist on using table names that are more than one word, you should use an underscore rather tha a space (like Login_table) to reduce the work involved with every query and prevent problems like the one you're having here.

Consider using a stored query that points to the form controls as parameters and avoid VBA variable concatenation and quote punctuation. Also, query design in Access GUI does not allow users to save query with syntax errors.
SQL
Adjust myForm to actual form name.
INSERT INTO [Login table]
(FirstName,
LastName,
Gender,
UserName,
Password,
Email,
Phone)
VALUES
(Forms!myForm!FirstName,
Forms!myForm!LastName,
Forms!myForm!Gender,
Forms!myForm!UserName,
Forms!myForm!Password,
Forms!myForm!Email,
Forms!myForm!Phone)
VBA
No need to close action queries and add SetWarnings to avoid update prompts.
DoCmd.SetWarnings False
DoCmd.OpenQuery "mySavedAppendQuery"
DoCmd.SetWarnings True

Password is a reserved word, so:
CurrentDb.Execute "INSERT INTO [Login table] (FirstName,LastName,Gender,UserName,[Password],Email,Phone) ...

I have just found that the the table had a field that was using a reserved name Note. By placing it in `` quotes (Note) fixed the issue.

Related

I am getting error on this line in my code

I am still developing my School management system. I want to create a multiple username and password for my system. But I am getting a Runt ime error 31314 on the Insert statement.
CurrentDb.Execute "INSERT INTO users(Username,Password,Email,Mobile,UserType) VALUES('" & Me.uname & "', '" & Me.upass & "', '" & Me.uemail & "', '" & Me.umobile & "', '" & Me.utype & "',)"
You can/should use a temporary parameter query:
The sql statement looks much more clear
It takes care of datatypes (no 's necessary)
It prevents SQL Injection
With CurrentDb().CreateQueryDef(vbNullString, _
"INSERT INTO users (Username, [Password], Email, Mobile, UserType) VALUES (p1, p2, p3, p4, p5)")
.Parameters("p1").Value = Me.uname
.Parameters("p2").Value = Me.upass
.Parameters("p3").Value = Me.uemail
.Parameters("p4").Value = Me.umobile
.Parameters("p5").Value = Me.utype
.Execute dbFailOnError
End With
If you want you can rename the parameters p1 to p5 to more describing names i.e. pUName and so on.
You have a trailing comma here:
"INSERT INTO users(Username,Password,Email,Mobile,UserType) VALUES('" & ... & Me.utype & "',)"
Trailing commma ---------------------------------------------------------------------------^
You should also surround the Password field with square brackets, since this is a reserved word in MS Access:
INSERT INTO users (Username, [Password], Email, Mobile, UserType)

SQL Statement to grab data from entry form to Data table in Microsoft Access 2010 VBA

So I'm setting up a database in MS Access 2010 (first time doing this). I can't seem to get the syntax of the SQL statement right. I want to take the data I have entered into a data entry form and insert a new row into a table, with that data. All of this using SQL in the VBA editor (only code I have available, all others are blocked)
Private Sub Add_Click()
Dim sSQL As String
sSQL = "INSERT INTO Data (Type, Name, Quantity, Amount, Class, Series, Client, Date1, Date2) VALUES " & _
"('" & Me!txtType & "','" & Me!txtName & "'," & Me!txtQuantity & "," & Me!txtAmount & ",'" & Me!txtClass & "','" & Me!txtSeries & "','" & Me!txtClient & "'," & Me!date1 & "," & Me!date2 & ")"
Debug.Print sSQL
CurrentDb.Execute sSQL
End Sub
So i Get the following error when i run the code, from the VBA editor :
"Run-time error '3134':
Syntax error in INSERT INTO statement."
And the printout of the SQL statement looks correct :
INSERT INTO Data (Type, Name, Quantity, Amount, Class, Series, Client, Date1, Date2)
VALUES ('Purhcase', 'TV', 500, 100, '', '', ' Bob', 05.08.2019, 05.08.2019)
Found the answer :
turns out one of the names of my data fields was a reserved word, therefore i simply put them all into [] and it solved the issue.
Thanks anyways for the help guys!

An explicit value for the identity column in table 'tableX' can only be specified when a column list is used and IDENTITY_INSERT is ON."

I am getting the error above saying that I cannot explicitly define the identity column without doing these things however, I am not trying to set the value of the identity column. I am merely trying to execute a basic insert statement using user input. I'm really stuck and need to get past this. Thoughts?
Public Sub ExecuteSQL(ByVal sql As String)
Using myConnection As New Data.SqlClient.SqlConnection(connString)
myConnection.Open()
Using cdmDatabaseCommand As New Data.SqlClient.SqlCommand(sql, myConnection)
cdmDatabaseCommand.ExecuteNonQuery()
End Using
End Using
End Sub
Dim insertSpray As String = ""
insertSpray = "INSERT INTO Spray VALUES ('" & sprayDate & "','" & timeStart & "','" & timeFinish & "','" & tankVolumeStart & "','" & tankVolumeFinish & "','" & comment & "','" & vehicleId & "','" & vehicleTime & "','" & siteType & "','" & area & "','" & applicatorOneId & "','" & applicatorTwoId & "','" & sprayLocationFeature & "','" & sprayStartLocationDescription & "','NULL','NULL','NULL','NULL','" & sprayEndLocationDescription & "');"
ExecuteSQL(insertSpray)
You're not specifying a column-list, so SQL Server assumes you want to insert into all columns, in table-order.
You need to change your syntax to specify the names of the columns you're inserting into (and leave out the identity column, obviously):
insert into Spray (SprayDate, TimeStart, ...)
values (...
Also note that your code is vulnerable to SQL injection attacks. You should look into using parameterized queries.
Try to explicitly make the columns of table Spray without the identity column.
Something like this:
insertSpray = "INSERT INTO Spray(Column1, Column2,...) VALUES (Value1,Value2,..)"

Syntax error creating an SQL query dynamically

I'm using VB6 and MS Access. my sql command is
insert into BatchInfo (BName,BDate,Currency) values('" & Me.txtBatchName.Text & "','" & Me.dtpBatchDate.Value & "','" & Me.cboCurrency.Text & "')
the output of the command at run time is
"insert into BatchInfo (BName,BDate,Currency) values('batch1','8/2/2012','AED')"
here is the schema of the BatchInfo Table
BatchID AutoNumber
BName Text
BDate Date/Time
Currency Text
I cannot find any syntax error. Please help.
Currency is a reserved word, escape it thusly;
insert into BatchInfo (BName, BDate, [Currency]) values (...
MS Access typically likes # signs around its dates:
insert into BatchInfo (BName,BDate,Currency)
values('" & Me.txtBatchName.Text & "','#" & Me.dtpBatchDate.Value & "#','" & Me.cboCurrency.Text & "')
You are using single quotes, not double quotes.
Try this
insert into BatchInfo (BName,BDate,Currency) values(""" & Me.txtBatchName.Text & """,#" & Me.dtpBatchDate.Value & #",""" & Me.cboCurrency.Text & """)

VBA select not returning any rows

Below query is not returning any rows into the listbox.There is no error message:
lstDiff.RowSource = "select TestScenario,TestId from tblTesting where empid= '" & Me.txtEmpId.Value & "' and testid= '" & Me.txtAutoNumber.Value & "'"
Could anyone help?
Your values in the field are numeric, so the extra single quotes aren't needed. Code should look like the following:
Me.lstDiff.RowSource = "select TestScenario,TestId from tblTesting where empid= " & Me.txtEmpId & " and testid= " & Me.txtAutoNumber & ";"
I've also dropped .Value from the field references, they're not harmful, but also aren't necessary.
And I've added a semi-colon to the end of your statement.
Depending on when/where you insert this code, you may need to add the following statement as well:
Me.lstDiff.Requery
You keep posting questions about the exact same WHERE clause with exactly the same apparent error in each one. SO users dutifully point out your error and then a few days later, you show up with a related question utilizing the same faulty WHERE clause.
DLookup Problem:
txtContSunStart1.Value = DLookup("Start1", "tblContract", _
"TestId = " & _
lstResults.Value & _
"" And "Day = 'Sunday'")
VBA Update Query:
DoCmd.RunSQL (" Update tbltesting set IsDiff ='Yes' where empid= " & Me.txtEmpId.Value & " and testid= " & Me.txtAutoNumber.Value & ";")
VBA SQL Problem
DoCmd.RunSQL ("insert into tbltesting (IsDiff)values ('Yes') where empid= '" & Me.txtEmpId.Value & "' and testid= '" & Me.txtAutoNumber.Value & "'")
And then in the current question:
lstDiff.RowSource = "select TestScenario,TestId from tblTesting where empid= '" & Me.txtEmpId.Value & "' and testid= '" & Me.txtAutoNumber.Value & "'"
You are having difficulties with exactly the same set of problems repeatedly.
Here are the rules for concatenating SQL strings with the correct delimiters in Access:
numeric values do not need delimiters:
"... AND testid= " & Me!txtAutoNumber
text values need quote delimiters. In Access, it's general practice to use double quotes, but much easier to use single quotes since it's a pain to type double quotes in a form that will work (typing """ or """" depending on context is counterintuitive and silly to me, so I always define a global constant that holds the double quote symbol and concatenate with that).
"... AND textfield=" & Chr(34) & Me!MyTextField & Chr(34)
date values use the # delimiter:
"... AND datefield=#" & Me!MyDateField & "#"
Boolean fields require no quotes and it works best to use True and False:
"... AND IsDiff=True"
These rules apply both to WHERE clause criteria and to SET statements in UPDATE queries. The rules apply in writing a SQL string that you pass to DoCmd.RunSQL or CurrentDB.Execute, as well as to writing SQL strings to be used as the recordsource of a form or report or as the rowsource of a combo box or listbox.
Personally, whenever I use SQL statements in code, I prefer to store the statement in a variable. While testing, on the line after you assign your statement to a variable, you can use Debug.Print to see what your SQL statement looks like after parsing your txtempid and txtautonumber. It would look something like this.
Dim sSQL as String
sSQL = "select TestScenario,TestId from tblTesting where empid= '" & Me.txtEmpId.Value & "' and testid= '" & Me.txtAutoNumber.Value & "'"
Debug.Print sSQL
lstDiff.RowSource = sSQL
Then as long as your immediate window is visible (Ctrl-G), you can see what your SQL statement really is. If it looks right in the immediate window, copy and paste it into the query builder and run it there.
Try running the query in your SQL Management Studio. Do you get any row(s) back?
Edit: Just noticed the access-tag. Are you sure your table contains at least one post with supplied ids?
My Access is a bit rusty, but if all else fails try using a recordset to capture the data from the SQL and loop through it adding the values to the list box. Example Code