doubled records with INSERT INTO sql statement inside VBA - sql

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.

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.

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 VBA syntax issue

This select statement works.
rs.Open "Select Company from Customers where Company LIKE '" & Replace(Range("K4").Value, "'", "''") & "%' "
This select statement doesn't work.
rs.Open "Select Company from Customers where '" & Range("N4").Value & "' LIKE '" & Replace(Range("K4").Value, "'", "''") & "%' "
I'm going to have a data validation drop down box where the user can pick between a few options so being able to change the second Company in the first select statement to the users selection would be handy. Something is wrong with the syntax because although it doesn't give me any errors it doesn't have any results.
You shouldn't quote the column name - notice there are no quotes in your first example.
rs.Open "Select Company from Customers where " & Range("N4").Value & _
" LIKE '" & Replace(Range("K4").Value, "'", "''") & "%' "

Excel and SQl Scripting

I have an Excel spreadsheet with 2000 rows of data. I need to create a SQL script to insert the data into a table. Below is the formula I used in Excel and it works for creating the insert statement, but how do I "Not Insert" if DiagnosisCode already exists?
= "INSERT INTO CommonDiagnosis (DiagnosisCode, Description, ActiveThru, ActiveThruEnteredBy, DiagnosisFormat) VALUES('" & A3 & "', '" & B3 & "', '" & C3 & "', '" & D3 & "', '" & E3 & "')"
You could try using an IF statement:
IF NOT EXISTS
( SELECT DiagnosisCode
FROM CommonDiagnosis
)
BEGIN
INSERT INTO CommonDiagnosis (DiagnosisCode,Description,ActiveThru,ActiveThruEnteredBy,DiagnosisFormat)
VALUES ('"&A3&"','"&B3&"','"&C3&"','"&D3&"','"&E3&"')
END;

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,..)"