Registering New Users in Database - sql

I´m trying to insert new users in my database, but every time the register button is pressed i get an error message saying:
Syntax error in INSERT INTO statement.
My Code:
Private Sub cmdReg_Click()
Dim sql As String
Dim recordCount As Long
Dim rst As Long
Dim conn As ADODB.Connection
sql = "insert into LoginPasswords (Teacher_LName, Teacher_FName, PassWord, UserName) values ('" & txtLast.Text & "','" & txtFirst.Text & "','" & txtPass.Text & "','" & txtUser.Text & "')"
If CurrentCon.State = adStateOpen Then
CurrentCon.Close
End If
CurrentCon.Open
CurrentCon.Execute sql
End Sub
How do i fix this.

Your insert statement will depend on the column data types of your database.
But lets just say, for example, that you have all text fields in your database. Then you need to do is remove the quotes you have around each of the values.
Something like this:
Set MySet = MyConn.Execute("INSERT INTO Table_Name (col1, col2, col3) VALUES (txtcol1.text,txtcol2.text,txtcol3.text)");
Try to remove the extra quotes from your query.
If there are any integer values, change your insert statement like:
INSERT INTO Table_Name VALUES(CInt(txtcol1.text),txtcol2.text,txtcol3.text);

Related

INSERT INTO - errors, but allows input into table

For reasons I cannot see I get the following error message:
Compile error: Method or data member not found
when I use the following:
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Once I click OK and use the refresh button the entry is put into the database, but each time I do an entry I have to go to the same process.
I would like to figure out what method or data is missing?
I should add that there is an outnumber primary key field on this table (Berth_ID), and each time I use the cmd_Add button a new ID number is created for the new record. This includes creating a new ID number for the new record that triggers the error.
Here is all the VBA associated with this form
Private Sub Form_Load()
DoCmd.RunCommand acCmdRecordsGoToLast
End Sub
Private Sub LOCATION_Change()
Me.txt_Cur_Flo = Me.LOCATION.Column(1)
Me.txt_Cur_Doc = Me.LOCATION.Column(2)
Me.txt_Cur_Ori = Me.LOCATION.Column(3)
End Sub
Private Sub cmd_Add_Click()
Dim strSQL As String
strSQL = " INSERT INTO BERTHAGE " _
& "(BOAT, LOCATION, BERTH_WEEK, BERTH_YEAR, BERTHED) VALUES " _
& Me.Add_Boat & "','" _
& Me.LOCATION & "','" _
& Me.txt_week & "','" _
& Me.txt_year & "','" _
& Me.In_Port & "');"
cmd_Clear_Click
End Sub
Private Sub cmd_Clear_Click()
Me.Add_Boat = ""
Me.LOCATION = ""
Me.txt_Cur_Flo = ""
Me.txt_Cur_Doc = ""
Me.txt_Cur_Ori = ""
Me.Add_Boat.SetFocus
End Sub
Private Sub cmd_Close_Click()
DoCmd.Close
End Sub
Consider the best practice of parameterization and not string concatenation of SQL mixed with VBA variables. Due to missing quotes, the compiler attempts to reference a column name and not its literal value. Instead, consider parameterization with defined types which is supported with Access SQL using QueryDefs. Notice below, SQL and VBA are complete separate.
SQL (save as stored query)
PARAMETERS prmBoat TEXT, prmLoc INT, prmBerthed INT;
INSERT INTO BERTHAGE (BOAT, LOCATION, BERTHED)
VALUES(prmBoat, prmLoc, prmBerthed)
VBA
Dim db As Database
Dim qdef As QueryDef
Dim strSQL As String
Set db = CurrentDb
Set qdef = db.QueryDefs("mySavedParamQuery")
' BIND PARAM VALUES
qdef!prmBoat = Me.Add_Boat
qdef!prmLoc = Me.LOCATION
qdef!prmBerthed = Me.In_Port
' EXECUTE ACTION QUERY
qdef.Execute
Set qdef = Nothing
Set db = Nothing
Even better, save your query with form controls intact and simply call OpenQuery:
SQL (save as stored query)
INSERT INTO BERTHAGE(BOAT, LOCATION, BERTHED)
VALUES(Forms!myForm!Add_Boat, Forms!myForm!LOCATION, Forms!myForm!In_Port)
VBA
Private Sub cmd_Add_Click()
Dim strSQL As String
DoCmd.SetWarnings False ' TURN OFF APPEND PROMPTS
DoCmd.OpenQuery "mySavedActionQuery"
DoCmd.SetWarnings True ' RESET WARNINGS
Call cmd_Clear_Click
End Sub
Missing opening parenthesis after VALUES. Also missing apostrophe in front of Me.Add_Boat. These special characters must always be in pairs, an even number by counting.
If Berth_Week and Berth_Year are number fields (and should be), don't use apostrophe delimiters.
If In_Port is a Yes/No field, don't use apostrophe delimiters.
The issue appears to be that I was doubling up the inputs into the 'week' and 'year' field. this was happening (I believe) because those text box fields were already accessing the week and year information directly from the default value on the BERTHAGE table. Essentially I went through each input and would run it individually waiting for the error to occur. Once it occurred I took it out of the INSERT INFO statement. With the removal of week and year, everything is working. That was a painful exercise, and still not complete, but I am back to a function form/DB so I'll take the small victories when they occur.
Private Sub cmd_Add_Click()
Dim strSQL As String
CurrentDb.Execute " INSERT INTO BERTHAGE " & "(BOAT, LOCATION, BERTHED) VALUES ('" & Me.Add_Boat & "'," _
& Me.New_Loc & "," _
& Me.In_Port & ");"
cmd_Clear_Click
DoCmd.Requery
End Sub`

Er : Syntax error in INSERT INTO statement Visual Basic 2017 using MC Access 2016 , oleDb 4.0

I am trying to insert data in my access database but i am getting a Syntax error in INSERT statemnt exception.Can someone please help me troubleshoot this error...Maybe my inset statement is not correct ?
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
If cmbTo.Text = "" Or cmbfrom.Text = "" Or cmbDay.Text = "" Or cmbMonth.Text = "" Or cmbYear.Text = "" Or cmbListBus.Text = "" Then
MsgBox("Please Insert Your Destination")
Else
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Hacke\source\repos\Student\Database\studentdatabase.mdb")
Dim insert As String = "INSERT INTO [BUSTICKET] VALUE ('" & cmbfrom.Text & "','" & cmbTo.Text & "','" & cmbDay.Text & "','" & cmbMonth.Text & "','" & cmbYear.Text & "','" & cmbListBus.Text & "');"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
cmd.ExecuteNonQuery()
MsgBox("Success")
conn.Close()
End If
Catch ex As Exception
MsgBox("Err : " & Err.Description)
End Try
End Sub
End Class
A few mistakes in your post has made it a bit difficult for us to understand.Anyway,i've submitted an edit of your post.
The problem i see so far is that you haven't defined which table you want to insert the data in.For example,if your table name is Students ,then a sample sql/OleDb statement might look like
"Seletct * from Students",ConnectionString
Note : In the following statement,i used (*) which means i am not selecting/targeting any particular column/cell but all the columns/cells.This statement is used for various purposes specially when retrieving data from the database.
However,your motive is to insert data in the database.
The INSERT statement for any database software(AFAIK) must include the Table name you are targeting,the Column/Cell headers/names.Let's assume your Table name is Students and you want to insert data in FirstName,LastNmae columns.Then a sample Insert statement may look like :
"Insert into Students(FirstName,LastName)values(#fname,#lname)", ConnectionString
Now,NOTE THAT i am not adding the values directly in the statement.you can do that if you want.However,in this sample insert statement,i am rather defining some parameter names like#Fname and #Lname.This will be used later on to finally insert data into the table's columns.
Now,if you go with my sample code,you must assign some values to these parameters from your application.We have 2 parameters now and they are #Fname and #Lname.We now need to add literal values to them.Let's assume the values are coming from TextBoxes.
MyOledbCommand.Add("#Fname",OledbDatatype.VarChar).Value = FNameTxtBox.Text
'Or you can use :
MyOledbCommand.AddWithValue("#Fname",FNameTxtBox.Text)
After you are done assigning the textboxes(or some string or whatever) as the values,it is time to execute the command so that the data inserts.For that,we generally call :
MyOleDbCommand.ExecuteNonQuery()
So,here's a full sample :
Dim con as New oleDbConnection = "ConnectionStringHere"
Con.open
Dim MyOleDbCommand as new OleDbCommand("Insert into Students(FirstName,LastName)values(#fname,#lname)", con)
MyOledbCommand.AddWithValue("#Fname",FNameTxtBox.Text)
MyOledbCommand.AddWithValue("#Lname",LNameTxtBox.Text)
MyOleDbCommand.ExecuteNonQuery
Con.Close
Hope this helps :)

Mass-Update Form w/VBA & SQL - ID not pulling correctly, records not being written to temp table

Edited since original posting: I realized that I had declared the volId variable as an Integer, but it's being read as a string. Once I changed the declaration to "Dim volId As String" the SQL code appears to be getting generated properly. Now I just need help in figuring out why the records are not being inserted into the temporary table.
I am trying to create a form that will allow the user to create multiple work records without having to re-enter the date, hours, and category information. (Ex: 10 people worked the same shift at the holiday party.) The way I plan to do this is to create a temp table, write a complete record to the table for each volunteer selected, then do an INSERT query to select everything from the temp table and insert the records into the real Work_Records table. (This second portion is not done yet. I'm debugging as I go, and have gotten stuck with the first part.)
The problem is that my records do not appear to actually be getting inserted into the temp table. I'm guessing that something is wrong with my SQL code.
Thanks!
My code:
Private Sub qryAppendMassWorkRecords_Click()
On Error Resume Next
DoCmd.RunSQL "DROP TABLE Tmp"
'Declare Vars
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rstRecords As Recordset
Dim dynamicSQL As String
Dim strSQL As String
Dim strTable As String
Dim hrsWorked As Integer
Dim DateWorked As Date
Dim pgmWorked As Integer
Dim volId As String
'Set initial values
Set db = CurrentDb
Set qdf = db.QueryDefs("qryTempAppendTable")
'Create new temp table to hold values from the form
strSQL = "CREATE TABLE Tmp (VolunteerID VARCHAR(20), DateWorked DATETIME, HoursWorked INT, WorkCategory INT);"
db.Execute strSQL
'Grab the values for the static vars and assign them
For Each ctl In Me.Controls
If ctl.Properties("Name") = "DateWorked" Then
DateWorked = ctl.Value
End If
If ctl.Properties("Name") = "HoursWorked" Then
hrsWorked = ctl.Value
End If
If ctl.Properties("Name") = "WorkCategory" Then
pgmWorked = ctl.Value
End If
Next ctl
'If combo box length > 0, create an INSERT statement to add the record to the temp table
For Each ctl In Me.Controls
If ctl.ControlType = acComboBox Then
'Category is the only combo box other than the ones for volunteer names; make sure it's not getting picked up
If ctl.Properties("Name") <> "WorkCategory" Then
'Verify that the field contains a name
If Len(ctl.Value) > 0 Then
volId = ctl.Value
'Reset the dynamicSQL to the initial code & add form values
dynamicSQL = "INSERT INTO Tmp VALUES (" _
& "'" & volId & "', #" & DateWorked & "#, " & hrsWorked & ", " & pgmWorked & ");"
db.Execute dynamicSQL
End If
End If
End If
qdf.SQL = dynamicSQL
Next ctl
DoCmd.OpenTable "Tmp", acViewPreview
End Sub
Try this:
dynamicSQL = "INSERT INTO Tmp VALUES ('" _
& volId & "', #" & DateWorked & "#, " & hrsWorked & ", " & pgmWorked & ");"
It will get a good Access SQL string:
INSERT INTO Tmp VALUES ('15', #12/02/2013#, 5, 3);
In Access Database, Datetime must be quoted with sharp #, like: #mm/dd/yyyy hh:mm:ss#,
or #yyyy-mm-dd hh:mm:ss#...
#12/02/2013#
More your VolunteerID is a string, so single quote like this:
'15'
Please notify, Access can only execute one single "INSERT" instruction, not multiple INSERT's as in MySQL. If you have many records, you must do a loop using VBA.
And run it to insert into Tmp, that you have not done:
db.Execute dynamicSQL
For example, this worked for me:
Sub qryAppendMassWorkRecords_Click()
On Error Resume Next
Dim strSQL As String
Dim db
'Set initial values
Set db = CurrentDb
strSQL = "CREATE TABLE Tmp (VolunteerID VARCHAR(20), DateWorked DATETIME, HoursWorked INT, WorkCategory INT);"
db.Execute strSQL
strSQL = "INSERT INTO Tmp VALUES ('242013', #12/2/2013#, 4, 39);"
db.Execute strSQL
DoCmd.OpenTable "Tmp", acViewPreview
End Sub

Use a ComboBox Value as part of an SQL Query? (MS Access 2010-2013)

I have a Database that we use to create Bills of Materials from Tags in AutoCAD. Because of the nature of this, I need to create 3 separate queries. One for our "Steel", one for our
"Non-Steel", and one for our "Uncut Tubes".
The SQL for the Queries is as follows:
Steel:
SELECT DISTINCTROW Sum([CUT-LENGTH-WEIGHT]) AS [SumOfCUT-LENGTH-WEIGHT], Sum([CUT-SHEET-WEIGHT]) AS [SumOfCUT-SHEET-WEIGHT], Sum([TOTAL-SHEETING-WEIGHT]) AS [SumOfTOTAL-SHEETING-WEIGHT], Sum([TOTAL-ITEM-WEIGHT]) AS [SumOfTOTAL-ITEM-WEIGHT]
FROM [13-1302 Cut-Lengths];
Non-Steel:
SELECT tbl2013BOM.fJobID, Sum(tbl2013BOM.fWeight) AS SumOffWeight
FROM tbl2013BOM
GROUP BY tbl2013BOM.fJobID
HAVING (((tbl2013BOM.fJobID)=23));
Uncut Tubes:
SELECT DISTINCT [13-1302 Cut-Lengths].[TOTAL-LENGTH-WEIGHT], [13-1302 Cut-Lengths].MATERIAL, [13-1302 Cut-Lengths].ORDER
FROM [13-1302 Cut-Lengths]
ORDER BY [13-1302 Cut-Lengths].ORDER;
I have a ComboBox that chooses the Job Number (For Main and Uncut Tubes, e.g. 13-1302) and a Textbox that displays the JobID (For Non-Steel).
Is there a way that I can set up the SQL shown above to look at the ComboBox and TextBox Values, instead of me having to change them by hand?
EDIT
I figured it all out now. (Thank you Elias)
Basically, I cannot use a Field on a table as a RecordSource in SQL, in other words, Combo26 cannot be the Table in an SQL Query. HOWEVER, what CAN be done is to use VBA to inject that value into an SQL Definition, then use that definition as a Recordsource.
I will place the code for my Button below so anyone can use it and reference it:
Private Sub Command27_Click()
Dim dbs As Database
Dim rstSQL As DAO.Recordset
Dim strSQL As String
Dim strSQL2 As String
Dim strSQL3 As String
Dim Field As String
Set dbs = CurrentDb
Field = [Forms]![frmBOM_Combined]![Text26].[Value]
strSQL = "SELECT DISTINCTROW Sum([CUT-LENGTH-WEIGHT]) AS [SumOfCUT-LENGTH-WEIGHT], Sum([TOTAL-SHEETING-WEIGHT]) AS [SumOfTOTAL-SHEETING-WEIGHT], Sum([TOTAL-ITEM-WEIGHT]) AS [SumOfTOTAL-ITEM-WEIGHT] FROM " & "[" & [Forms]![frmBOM_Combined]![Text26].[Value] & "]" & ";"
strSQL2 = "SELECT tbl2013BOM.fJobID, Sum(tbl2013BOM.fWeight) AS SumOffWeight FROM tbl2013BOM GROUP BY tbl2013BOM.fJobID HAVING (((tbl2013BOM.fJobID)= " & [Forms]![frmBOM_Combined]![Combo25].[Value] & "));"
strSQL3 = "SELECT DISTINCT [TOTAL-LENGTH-WEIGHT], [MATERIAL], [ORDER] FROM " & "[" & [Forms]![frmBOM_Combined]![Text26].[Value] & "]" & " ORDER BY [ORDER];"
Debug.Print strSQL
Debug.Print strSQL2
Debug.Print strSQL3
DoCmd.OpenForm ("frmEstWeight")
Forms!frmEstWeight.RecordSource = strSQL
Forms!frmEstWeight.frmTestBomWeight.Form.RecordSource = strSQL2
Forms!frmEstWeight.frmTotalLengthWeight.Form.RecordSource = strSQL3
End Sub
This is working exactly as it should with no errors or anything.
This is within a form correct?
If so, replace the manual values you put in with
REST OF THE QUERY HERE " & Me!Controlname.value & " REST OF THE QUERY HERE
and if you are using something with a control source then just reset the control source value.
me!ControlWithResult.control source = "SELECT tbl2013BOM.fJobID, Sum (tbl2013BOM.fWeight) AS SumOffWeight
FROM tbl2013BOM
GROUP BY tbl2013BOM.fJobID
HAVING (((tbl2013BOM.fJobID)=" & me!controlname.value & "));"
For Non-Steel try:
On the VBA for the popup form
me!Combo25.rowsource = "SELECT tbl2013BOM.fJobID, Sum(tbl2013BOM.fWeight) AS SumOffWeight
FROM tbl2013BOM
GROUP BY tbl2013BOM.fJobID
HAVING (((tbl2013BOM.fJobID)=" & forms!MAINFORMNAME! &"));

Inserting into a different table from a form

I am trying to make an event when iputing data in a form on access, after the text box looses focus, if the box is not null I want the ID and the value to get stored into another table. After trying with the code below I get "Runtime error 3061 Too few parameters Expected 1". I have checked in debug mode and the values are getting carried over and brought to the string.
Private Sub Consolidate_LostFocus()
Dim queryString As String
queryString = "INSERT INTO [ReportMasterTable]([#], [Notes]) VALUES(" & [#].Value & ", " & [Consolidate].Value & ")"
If Consolidate.Text <> vbNullString Then
CurrentDb.Execute (queryString)
End If
End Sub
If either the # or the Notes fields in ReportMasterTable is text data type, you must add quotes around the values you attempt to INSERT.
For example, if both fields are text type:
queryString = "INSERT INTO [ReportMasterTable]([#], [Notes])" & vbCrLf & _
"VALUES ('" & [#].Value & "', '" & [Consolidate].Value & "')"
The situation will be more complicated if either [#].Value or [Consolidate].Value contains a single quote. You could double up the single quotes within the inserted values. However it might be easier to just switch to a parameterized query ... the quoting problem would go away.
Dim db As DAO.database
Dim qdf As DAO.QueryDef
Dim strInsert As String
strInsert = "PARAMETERS hash_sign Text (255), note_value Text (255);" & vbCrLf & _
"INSERT INTO [ReportMasterTable]([#], [Notes])" & vbCrLf & _
"VALUES (hash_sign, note_value)"
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strInsert)
qdf.Parameters("hash_sign").value = Me.[#]
qdf.Parameters("note_value").value = Me.[consolidate]
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
You could also save the SQL statement as a named query and open and execute that instead of rebuilding the statement every time your procedure runs.
Is there any reason why you do not wish ti bind the form to the ReportMasterTable?
If you really have a control and field called #, you are facing a world of trouble.
If you have bound the form to ReportMasterTable and are also updating in a query, you are going to run into problems.
The lost focus event is a very bad event to choose, any time anyone tabs through the form, the code will run. After update would be better.
You are updating a text data type, but you have not used quotes.
"INSERT INTO [ReportMasterTable]([#], [Notes]) VALUES(" & [#].Value _
& ", '" & [Consolidate].Value & "')"