Problem with INSERT INTO statement, new to access - ms-access

I got thrown into a project at work and I'm trying to fight my way through it. I'm trying to write records to a table from a form. I want to select from two combo boxes and then send the selections plus the time to a table.
Here is what I have
Private Sub cmdClockin_Click()
Dim StrSQL As String
Dim Cin As Date
Dim Ein As String
Dim Jin As String
Cin = Now()
Ein = Me.ComboEmp
Jin = Me.comboJob
StrSQL = "INSERT INTO Records (proStart, proEmployee, proJob) VALUES ('" & Cin & "', '" & Ein & "', '" & Jin & "');"
DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True
End Sub
I do not get any errors, but nothing gets written to the table.
I have been scouring different websites and for some reason I cant figure out what I'm doing wrong. Any help would be amazing
Thanks,
Chris

Insert Now directly, consider if Ein or Jin are numeric (thus no quotes), and do check your SQL:
StrSQL = "INSERT INTO Records (proStart, proEmployee, proJob) VALUES (Now(), '" & Ein & "', '" & Jin & "');"
MsgBox StrSQL

First suggestion change table name from Records to some other name. You need to qualify time as Date/Time by a hash # symbol instead of single quote (') for date data type. Check below
StrSQL = "INSERT INTO Records (proStart, proEmployee, proJob) VALUES (#" & Cin & "#, '" & Ein & "', '" & Jin & "');"

Related

Make textbox null if empty

hello I have a userform in excel which is connected to mysql server.
everything works except when I leave the textbox for date empty, I get an error that the value for date is incorrect
on further research I found that the textbox return zero length string when empty and mysql allows only null.
Is there anyway to set the textbox as null when I click on the save button.
Heres my attempt at a solution, hopefully this will help.
Basically its a quick check to see if the textbox in question is empty, and if so, then make it null:
If textbox1.value = "" then
textbox1.value = null
end if
Finally a solution, but this will be a pain in the b, if you have 20 date columns. Unfortunately I have 20 date columns..:(
This is the code which for me, hope this helps someone in the future
Private Sub CommandButton1_Click()
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
strCon = "Driver={MySQL ODBC 5.3 Unicode Driver};Server=localhost;Database=sample;" _
& "User=root;Password=Password;Option=3;"
cn.Open strCon
If txt5.Value = "" Then
SQLStr = "insert into sample.details (ID,Name,Age,Gender,Date_of_Birth) values ('" & txt1.Value & "', '" & txt2.Value & "','" & txt3.Value & "','" & txt4.Value & "',Null);"
cn.Execute SQLStr
Else
SQLStr = "insert into sample.details (ID,Name,Age,Gender,Date_of_Birth) values ('" & txt1.Value & "', '" & txt2.Value & "','" & txt3.Value & "','" & txt4.Value & "','" & Format(txt5.Value, "yyyy-mm-dd") & "');"
cn.Execute SQLStr
End If
End Sub

Importing data from excel to mysql database using vba

I´m trying to import data into a MySQL Database, i have searched for many examples and solutions but it didn´t working and i have no idea why. Below is my vba code. I am getting runtime error 2147217900(80040e14) saying that you have an error in your sql syntax; chek the manual that corrsponds to your mysqlfor the right syntax to use near '='41282'
Sub Getdata()
Dim conn As New ADODB.Connection
Dim server_name As String
Dim database_name As String
Dim user_id As String
Dim password As String
Dim a As Long ' counter
Dim i As Long, j As Variant, k As Long
Dim sqlstr As String ' SQL to perform various actions
Dim table1 As String, table2 As String
Dim field1 As String, field2 As String
Dim field3 As String
Dim rs As ADODB.Recordset
sqlstr = "INSERT INTO" & table1 & "SET" _
& field1 & " = '" & i & "', " _
& field2 & " = '" & j & "', " _
& field3 & " = '" & k & "'"
conn.Execute sqlstr
Next a
End With
skipwrite:
End Sub
Simply, space out the table name and SET command in the concatenated string. Also, add tick marks before and after due to the reserved words used in column names (which by the way should be avoided as best practices):
sqlstr = "INSERT INTO " & table1 & " SET " _
& "`" & field1 & "` = '" & Format(i, "YYYY-MM-DD") & "', " _
& "`" & field2 & "` = '" & j & "', " _
& "`" & field3 & "` = '" & k & "';"
Also as mentioned by #Lelio, format the date to read properly into a MySQL Date column.
Date in Excel are stored as number of days between 1899-12-31 and the actual date. What you are trying to do is to store a number in a field that has a numeric format.
41282 is the number of days. So you should calculate something like:
'1899-12-31' + 'i days'
to get the date in mysql format (that by default is YYYY-MM-DD). I don't know the exact string manipulation command for VBA to get this but on the MYSQL side this should fix your error

Access VBA: SQL query causes UPDATE syntax error

I have a database with linked tables- Staff, Courses and Training_Record. Each staff member has a numeric primary key, as does each course and each entry in the Training_Record table. The Staff_ID and Course_ID in the Training_Record reference records in Staff and Courses.
When a staff member or course is added, the Training_Record (fields: Staff_ID, Course_ID, Date_Taken, Notes) has staff,course records inserted- so adding staff member 1 would insert records (1,1,,,), (1,2,,,) etc, adding course 8 would insert records (1,8,,,), (2,8,,,) and so on. This works.
I then have a form to record training. The user selects the course, enters the date and selects staff members from a listbox. I have a save button which triggers VBA code. The date and course are pulled from the boxes and I loop round the listbox, concatenating selected staff members into a string. This all works and a message box displays, verifying that. Then, an update SQL query should be run, updating the Training_Record.
The problem I have is with the SQL update. I have an update query that will work in the SQL query editor, though it uses written in variables:
UPDATE Training_Record
SET Date_Taken = '12/12/12'
WHERE Staff_ID IN (1,2,3,4,5) AND Course_ID = 4
This updates the Training_Record to show that staff 1,2,3,4 and 5 took course 4 on 12/12/12. However, in VBA this will not work. This is my SQL query in VBA:
strSQL = "UPDATE Training_Record" _
& "SET Date_Taken = (" & strDate & ")" _
& "WHERE Staff_ID IN (" & strCriteria & ") AND Course_ID = (" & strCourse & ")"
DoCmd.RunSQL strSQL
The error that the code generates is "Run-time error '3144': Syntax error in UPDATE statement." and the debugger highlights the DoCmd.RunSQL statement following the query.The entire VBA code:
Private Sub SaveTraining_Click()
Dim db As DAO.Database
Dim VarItem As Variant
Dim strCriteria As String
Dim strDate As Variant
Dim strCourse As Variant
Dim strSQL As String
Set db = CurrentDb()
'Extract the course ID and the training date from the form
strCourse = Me!CourseID.Value
strDate = Me!TrainingDate.Value
'Dealing with empty boxes- zero length
If IsNull(strCourse) Then
MsgBox "Please select a course." _
, vbOKOnly, "No course selected"
End If
If IsNull(strDate) Then
MsgBox "Please enter a date." _
, vbOKOnly, "No date given"
End If
If StaffMembers.ItemsSelected.Count = 0 Then
MsgBox "Please select staff members." _
, vbOKOnly, "No staff members"
End If
If (Not IsNull(strCourse)) And (Not IsNull(strDate)) And (StaffMembers.ItemsSelected.Count > 0) Then
'Extract each selected member and concatenate into a string for sql query
For Each VarItem In Me!StaffMembers.ItemsSelected
strCriteria = strCriteria & "," & Me!StaffMembers.ItemData(VarItem)
Next VarItem
'Gets rid of extra comma on query string
strCriteria = Right(strCriteria, Len(strCriteria) - 1)
'Message box
MsgBox ("Staff: " & strCriteria & vbNewLine & "Date: " & strDate & vbNewLine & "Course: " & strCourse & vbNewLine & "No. Selected staff: " & StaffMembers.ItemsSelected.Count)
strSQL = "UPDATE Training_Record" _
& "SET Date_Taken = (" & strDate & ")" _
& "WHERE Staff_ID IN (" & strCriteria & ") AND Course_ID = (" & strCourse & ")"
DoCmd.RunSQL strSQL
End If
Set db = Nothing
End Sub
TL;DR I can't make a SQL UPDATE query run in VBA
I've got a feeling that it's an error in syntax somewhere, but I can't find where. Any ideas/advice would be much appreciated, thanks.
I think you are simply missing spaces at the end of the lines
You old query print out
UPDATE Training_RecordSET Date_Taken = ()WHERE Staff_ID IN () AND Course_ID = ()
as you can see there will be a name collision before keywords SET and WHERE
therefore change your strSQL to
strSQL = "UPDATE Training_Record " _
& "SET Date_Taken = (" & strDate & ") " _
& "WHERE Staff_ID IN (" & strCriteria & ") AND Course_ID = (" & strCourse & ")"
which prints out as (with no values provided)
UPDATE Training_Record SET Date_Taken = () WHERE Staff_ID IN () AND Course_ID = ()
which in terms of SQL syntax is correct
If I were you I would also check the data types of columns in your Training_Record table
Usually (and this applies to Type-mismatch error),
for dates you wrap the variable or value on both sides with #
example & "SET Date_Taken = (#" & strDate & "#) ...
for strings you use single quotes '
example WHERE Operator_Name = ('" & operName & "') ...
for numerical values you do not need to use anything but casting to provide the correct data type
My guess:
strSQL = "UPDATE Training_Record" _
& "SET Date_Taken = (#" & Format(strDate, "mm\/dd\/yyyy") & "#)" _
& "WHERE Staff_ID IN (" & strCriteria & ") AND Course_ID = (" & strCourse & ")"
If staff_ID is a string:
strSQL = "UPDATE Training_Record" _
& "SET Date_Taken = (#" & Format(strDate, "mm\/dd\/yyyy") & "#)" _
& "WHERE Staff_ID IN ('" & strCriteria & "') AND Course_ID = (" & strCourse & ")"

Classic ASP mysql INSERT getting result Operation is not allowed when the object is closed

I have this code:
Set oConnection = Server.CreateObject("ADODB.Connection")
Set oRecordset = Server.CreateObject("ADODB.Recordset")
oConnection.Open "DRIVER={MySQL ODBC 5.1 Driver};SERVER=localhost;UID=xxxx;PWD=xxxx;DATABASE=xxxx; OPTION=3;"
Sqltemp = "INSERT INTO rsvptable (fname, lname, fbid, rsvp, streetaddress, city, state, zip, streetaddress2, cellphone, acode) " & _
"VALUES ('" & firstName & "', '" & lastName & "', " & fb & ", 0, '" & address1 & "', '" & city & "', '" & strState & "', " & zip & ", '" & address2 & "', " & cell & ", " & returnedNums & ")"
set newAdd = oConnection.execute(Sqltemp)
if newAdd.EOF then
response.write "end"
else
response.write "not end"
end if
And it keeps telling me this:
ADODB.Recordset error '800a0e78'
Operation is not allowed when the object is closed.
/add.asp, line 136
line 136 is this:
if newAdd.EOF then
What would i be overlooking here?
UPDATE
found my answer here! :o)
How to tell if a db update was successful?
two things:
you define oRecordset as the recordset, but then use & check eof on newAdd
Why are you trying to populate a recordet from an insert query?
http://www.w3schools.com/ado/met_conn_execute.asp
The results are stored in a new Recordset object if it is a
row-returning query. A closed Recordset object will be returned if it
is not a row-returning query.
INSERT is not a row-returning query, thus it returns a closed recordset, thus you can't .EOF it. Check the Rows Affected bu passing a variable as the second argument to Execute. If RowsAffected is 1, then you're set.

DoCmd.RunSQL in Access not providing expected results

I've done this a zillion times, and I don't know what's changed.
Private Sub Foo()
dim rst as DAO.Recordset
set rst = CurrentDB.OpenRecordset("Select * From Table1;", dbOpenDynaset)
rst.movefirst
Do Until rst.EOF
DoCmd.RunSQL INSERT INTO Table2 (Last, First, Gender) VALUES (" & "' & rst!Last & '" & ", " & "' & rst!First & '" & ", " & "' & rst!Gender & '" & ");"
rst.MoveNext
Loop
End Sub
If I do this, the values inserted into Last, First and Gender are '" & rst!ColumnName & "' versus the actual data from the column.
If I omit the single quotes it works until it comes across a last name with a hypen or aposttrophe and then it throws a syntax error.
But I've done this same thing in code a zillion times the last 6 years and it's always worked and for whatever reason on this new project it's not proving the results I am used to.
Any ideas?
You seem to have that a bit mixed up:
DoCmd.RunSQL "INSERT INTO Table2 (Last, First, Gender) VALUES ('" & _
& rst!Last & "', '" & rst!First & "', '" & rst!Gender & "');"
Note that if you have names that contain apostrophes, the above will fail, so it is a good idea to escape them like so:
DoCmd.RunSQL "INSERT INTO Table2 (Last, First, Gender) VALUES ('" & _
& Replace(rst!Last,"'","''") & "', '" & Replace(rst!First,"'","''") _
& "', '" & rst!Gender & "');"
The other point that I wonder about is why are you doing this in steps? Why not:
strSQL = "INSERT INTO Table2 (Last, First, Gender) " _
& "SELECT Last, First, Gender FROM Table1 "
CurrentDB.Execute strSQL, dbFailOnError