I am getting error on this line in my code - sql

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)

Related

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

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.

doubled records with INSERT INTO sql statement inside VBA

I'm trying to realise a simple sign up structure, and I am really new in VBA and Access.
At the instruction INSERT TO it should add a record to the table USER. but it adds 2 identical records that have just a different userID, generated by the Automatic Numeration. Then I want to copy the last generated UserID in global variable valID, so that I can insert this UserID in a another table.
What am I doing wrong?
DoCmd.RunSQL ("INSERT INTO User ([Type], [FiscalCode], [Name], [Surname], [Birthdate], [Gender], [phoneNumber], [email], [country], [city], [postalCode], [street], [houseNumber])VALUES ('" & valtype & "', '" & valfis & "', '" & valname & "', '" & valsur & "', '" & valdata & "', '" & valgen & "', '" & valphone & "', '" & valemail & "','" & valcountry & "', '" & valcity & "', '" & valcode & "', '" & valstreet & "', " & valnum & ")")
valID = DLookup("[UserID]", "User", "[FiscalCode] = '" & valfis & "'")
after this code I want to do another instruction of the type insert to in a different table to insert in this new table as primary key the UserId I just obtained. this is the only other INSERT INTO inside the code.
For this to happen, most likely form is bound to table and controls are bound to fields so user is inputting data into controls and then code runs INSERT as well thereby creating two records of same data.
A record is committed to table when one of the following happens:
1) table or query or bound form is closed
2) move to another record
3) run code to save
Remove the code.
Use form/subform arrangement for inputting parent record as well as dependent record in 'another' table.

Insert data to a SQL Server database that contains apostrophes

I'm making this program on Vb.net 2012 that has a connection to SQL Server 2012.
One of the columns of this database table is Description, and in some cases the date may include apostrophes, for example... 'chainsaw 15'3" X 1 1/2 X .050 X 3/4'
When I run the query the apostrophe that is between the data causes an error at the syntax of the query, this is the query line in VB.net.
CMD.CommandText =
"INSERT INTO Table_ARTICLES
(NUMPART, DESCRIPTION, LOCATION, MAX, ACTUAL, MIN, Unidad_de_medida)
VALUES ('" & txtNumParte.Text & "', '" & txtDescripcion.Text & "',
'" & txtLocaclizacion.Text & "', '" & txtMaximo.Text & "', '" & txtActual.Text & "',
'" & txtMin.Text & "', '" & cmbUnidad.Text & "')"
Does anybody know how to make this query accept those characters on the query?
As #pmbAustin pointed out, is a terrible idea to build sql statements via string concatenation due to SQL Injection attacks and other problems. The approach you should use is called a parametrized query:
CMD.CommandText = "INSERT INTO (NUMPART, DESCRIPTION, LOCATION, MAX, ACTUAL,
MIN, Unidad_de_medida)
VALUES (#NUMPART, #DESCRIPTION,#LOCATION,#MAX,#ACTUAL,#MIN,#UNIDAD_DE_MEDIDA)"
And then:
CMD.Parameters.Add("#NUMPART",txtNumParte.Text);
CMD.Parameters.Add("#DESCRIPTION",txtDescripcion.Text);
//...and so on
CMD.ExecuteNonQuery();
Please use parameterized SQL (i.e. stored procedures) to prevent SQL injection and the like.
As for your question, you would want to replace the single quote (apostrophe) with two single quotes before you add it as a parameter. This way the first one acts as an escape character which will allow for the apostrophe to be inserted into the database.
Example:
txtNumParte.Text.Replace("'", "''")

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 & """)