Automation error using SQL queries in a loop - sql

I'm trying to run a loop through a table that takes relevant information and then inserts it into a VFP9 .dbf table. However, I keep getting an automation error ('-2147217913 (80040e07)'). It seems to run the first time just fine, inserting into a table a single time before erroring out. I've made it print out the string every time with the execution part of the code commented out, but the SQL looks perfectly fine. What is the issue here?
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
sConnString = "DSN=Visual FoxPro Tables;UID=;SourceDB=s:\accounting\db;SourceType=DBF;Exclusive=No;BackgroundFetch=Yes;Collate=Machine;Null=Yes;Deleted=Yes;"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
For i = 1 To [RawTable].Rows.Count
vStatement = "dong!"
vAccount = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("account").Index)
vCardUser = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("card member").Index)
vDate = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("date").Index)
vDesc = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("description").Index)
vAmount = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("amount").Index)
MsgBox "INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "','" & vDate & "','" & vDesc & "'," & vAmount & ")"
conn.Execute ("INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "','" & vDate & "','" & vDesc & "'," & vAmount & ")")
Next i
MsgBox "done :)", vbInformation
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing
EDIT: Here is an example of what the table will look like.
date receipt description card member account # amount account
07/01/2016 Purchase Employee XXXX-XXXXXX-XXXXX 9.95 41000-000-00
07/01/2016 Purchase Employee XXXX-XXXXXX-XXXXX 33 41000-000-00
06/29/2016 Purchase Employee XXXX-XXXXXX-XXXXX 64 41000-000-00

Visual Foxpro doesn't like receiving dates as just String literals or series of numbers. Try using the CTOD function (Characters to Date) and see if that resolves the problem. The Execute line should look like:
conn.Execute ("INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "',CTOD('" & vDate & "'),'" & vDesc & "'," & vAmount & ")")

Related

Syntax error when copying data from Excel userform to Access table

When trying to copy data from an Excel userform in to an Access table via SQL I am encountering an error on a field that is a Yes/No type in the database. How can I format the info correctly so that it updates the database?
I have looked at some other examples of copying data into the Yes/No fields in Access, as well as trying my code in a number of different formats, with double quotations, single quotations & as it appears below
Dim oConn As ADODB.Connection
Dim oCm As ADODB.Command
Dim iRecAffected As Integer
If Me.TBField.Visible = False Then
'Update office users
Init1 = Left(Me.TxtName1, 1) & Mid$(Me.TxtName1, InStr(Me.TxtName1, " ") + 1, 1)
Select Case Me.LblFraOffice.Caption
Case Is = "Add User"
Set oConn = New ADODB.Connection
oConn.Open sConn
Set oCm = New ADODB.Command
oCm.ActiveConnection = oConn
If RbUser.Value = True Then
oCm.CommandText = "INSERT Into Users (Name, Username, Initials, Process, FLM, FLM_ID, User, JobRole) " & _
"VALUES ('" & TxtName1.Value & "','" & TxtUname1.Value & "','" & Init1 & "','" & TxtProcess1.Value & "','" & TxtFLM.Value & "','" & TxtFLMID.Value & "', True ,'" & TxtPosition1.Value & "')"
ElseIf RbAdmin.Value = True Then
oCm.CommandText = "INSERT Into Users (Name, Username, Initials, Process, FLM, FLM_ID, JobRole, User) " & _
"VALUES ('" & TxtName1.Value & "','" & TxtUname1.Value & "','" & Init1 & "','" & TxtProcess1.Value & "','" & TxtFLM.Value & "','" & TxtFLMID.Value & "', True ,'" & TxtPosition1.Value & "')"
ElseIf RbManager.Value = True Then
oCm.CommandText = "INSERT Into Users (Name, Username, Initials, Process, FLM, FLM_ID, JobRole, User) " & _
"VALUES ('" & TxtName1.Value & "','" & TxtUname1.Value & "','" & Init1 & "','" & TxtProcess1.Value & "','" & TxtFLM.Value & "','" & TxtFLMID.Value & "', True ,'" & TxtPosition1.Value & "')"
End If
'MsgBox oCm.CommandText
oCm.Execute iRecAffected
oConn.Close
When pressing submit on the userform this should add a newly created user into the database table. If I remove the User field (and the associated true/false) it works. But my users can be users, admins or managers
At present I receive an error message
Run-time error '-2147217900 (80040e14)': Syntax error in INSERT INTO statement
Column name User is the reserved keyword. Can you add square brackets around the keyword to fix the issue:
INSERT Into Users (Name, Username, Initials, Process, FLM, FLM_ID, [User], JobRole)
or you can rename the column name to a non-reserved keyword to sovle this error.

error 3075 syntax missing comma

I've looked in many places on the internet trying to solve this problem but I can't seem to figure it out. Could someone just provide a second set of eyes and just check where I may have gone wrong with the syntax?
The error says RunTime error 3075,
"Syntax error (comma) in query expression
'('test',12/15/2014','Primary')'.
Originally it worked when I had this split into four different INSERT statements, but when I combined it, it stopped working
SQL = "INSERT INTO WeeksonCall([Employee], [Week], [Prim/Backup]) VALUES (('" & _ cboName.Column(1) & "','" & cboWeek.Column(1) & "','" & cboPrimBack.Value & _
"'),('" & cboName2.Column(1) & "','" & cboWeek.Column(1) & "','" & cboPrimBack2.Value & _
"'),('" & cboName.Column(1) & "','" & cboWeek2.Column(1) & "','" & cboPrimBack2.Value & _
"'),('" & cboName2.Column(1) & "','" & cboWeek2.Column(1) & "','" & cboPrimBack.Value & "'))"
That is not proper syntax in MS Access. You will have to insert the records individually like:
DoCmd.SetWarnings False
SQL = "INSERT INTO WeeksonCall(Employee, Week, [Prim/Backup]) " & _
"VALUES ('" & _ cboName.Column(1) & "','" & cboWeek.Column(1) & "','" & cboPrimBack.Value & "')"
SQL = "INSERT INTO WeeksonCall(Employee, Week, [Prim/Backup]) " & _
"VALUES ('" & cboName2.Column(1) & "','" & cboWeek.Column(1) & "','" & cboPrimBack2.Value & "')"
SQL = "INSERT INTO WeeksonCall(Employee, Week, [Prim/Backup]) " & _
"VALUES ('" & cboName.Column(1) & "','" & cboWeek2.Column(1) & "','" & cboPrimBack2.Value & "')"
SQL = "INSERT INTO WeeksonCall(Employee, Week, [Prim/Backup]) " & _
"VALUES ('" & cboName2.Column(1) & "','" & cboWeek2.Column(1) & "','" & cboPrimBack.Value & "')"
DoCmd.SetWarnings True
EDIT: You can stop the user prompts by using SetWarnings = False before the inserts. Then turn the warnings back on after the inserts via DoCmd.SetWarnings True.
Can you please provide the remainder of the VBA you're using in order to ask the user for input? As far as I see you're only assigning a string to the SQL variable. Where is the rest of your code?
And, by the way, I never like using:
DoCmd.SetWarnings False
Instead use the module below, that way if you do get an error you can deal with it instead of hidding it:
Option Compare Database
Option Explicit
Public Function Run_Safe_SQL(strSQL)
On Error GoTo Error_Handler
Dim db As DAO.Database
Set db = CurrentDb()
db.Execute strSQL, dbFailOnError
DBEngine.Idle dbRefreshCache
' DoEvents
Exit_Here:
'Cleanup
Set db = Nothing
strSQL = ""
Exit Function
Error_Handler:
MsgBox Err.Description & " " & Err.Number
End Function

VB the microsoft access database engine could not find the object

I'm receiving the following run time error on VB (Excel 10) "the microsoft access database engine could not find the object". The "Database" is a defined named within a worksheet but it wont pick it up. Any ideas would be hugely appreciated!!
Sub ConnectDB()
If cnn.State <> adStateOpen Then
Dim strFileName As String
strFileName = "O:Children's Fund\APS 2014-15\Refrerral - Allocation Database.xlsx"
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & strFileName & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes"";"
End If
End Sub
Sub CopyData()
ConnectDB
Dim rst As New ADODB.Recordset
Dim CurrentID As Long
Dim vbResult As VbMsgBoxResult
rst.Open "SELECT * FROM [A2:M1000];", cnn, adOpenStatic, adLockReadOnly
If Not rst.EOF Then
rst.MoveLast
CurrentID = rst("RefNumber")
CurrentID = CurrentID + 1
Else
CurrentID = 1
End If
Dim sql As String
sql = "Insert into [Database] (refnumber, surname, FirstName, DOB, ReferrerEmail, PreferredSetting, MotherEmployment, FatherEmployment, OtherEmployment, Other1Employment, Attendance, Exclusions) values ('" & _
CurrentID & "','" & [FormSurname] & "','" & [FormFirstName] & "','" & [FormDOB] & "','" & [FormEmail] & "','" & [FormPreferred] & "','" & [FormMother] & "','" & [FormFather] & "','" & [FormOther] & "','" & [FormOther1] & "','" & [FormAttendance] & "','" & [FormExclusions] & "')"
cnn.Execute (sql)
MsgBox "Record Saved to Database"
DisconnectDB
End Sub
Sub DisconnectDB()
If cnn.State <> adStateClosed Then
cnn.Close
Set cnn = Nothing
End If
End Sub
Many Thanks
Sam

Conversion failed when converting date and/or time from character string

sql = "insert into tbl_nurse(nurseid,nursename,deptname,dob,doj,qualification,salary)"
sql = sql & "values('" & txtNurseid.Text & "','" & TxtNursename.Text & "','" & Cmbdept.Text & "',convert(date,'" & DateTimePicker1.Value & "',103),convert(date,'" & DateTimePicker2.Value & "',103),'" & Txtqualification.Text & "','" & txtsalary.Text & "')"
conn.Execute(sql)
You should use sql-parameters to avoid sql-injection and to prevent from conversion issues like this.
Example presuming SQL-Server:
Const sql = "INSERT INTO tbl_nurse(nurseid,nursename,deptname,dob,doj,qualification,salary)" & vbCrLf & _
"VALUES(#nurseid, #nursename, #deptname, #dob, #doj, #qualification, #salary)"
Using con = New SqlConnection("Insert Your Connection String Here")
Using cmd = New SqlCommand(sql, con)
cmd.Parameters.AddWithValue("#nurseid", txtNurseid.Text)
cmd.Parameters.AddWithValue("#nursename", TxtNursename.Text)
cmd.Parameters.AddWithValue("#deptname", Cmbdept.Text)
' -- No conversion problems anymore because you pass a DateTime -- '
cmd.Parameters.AddWithValue("#dob", DateTimePicker1.Value)
' ... other parameters ... '
con.Open()
Dim affectedRecords As Int32 = cmd.ExecuteNonQuery()
End Using
End Using
Try to change like this ..
sql = "insert into tbl_nurse(nurseid,nursename,deptname,dob,doj,qualification,salary)"
sql = sql & " values('" & txtNurseid.Text & "','" & TxtNursename.Text & "','" & Cmbdept.Text & "',#" & format(DateTimePicker1.Value.Date) & "#,#" & format(DateTimePicker2.Value.Date) & "#,'" & Txtqualification.Text & "','" & txtsalary.Text & "')"
conn.Execute(sql)
As Tim Scmelter said .. you better use parameterize input
Add Parameters as below and it works like charm
cmnd.Parameters.Add("#date_time", SqlDbType.DateTime).Value = datetime.Date;
The original post is here:
https://www.codeproject.com/Answers/552202/Conversionplusfailedpluswhenplusconvertingplusdate#answer3

how to store data from vb.net to access a database

I am using an Access database and vb.net 2010. I have created a table in the database with columns for title, datein, dateout and roomnymber. In vb.net 2010 I made a distinguished title = combobox, datein and dateout = DateTimePicker. When I click on F5, an error occurs: INSERT INTO Syntax Error in statement. Here's my code:
Dim sql As String
sql = "INSERT INTO tcekin(title,firstname,lastname,address,country,company,roomnumber,datein,dateout,rommtype,note)" & "VALUES('" & ComboBox1.Text & _
"','" & txtFirstName.Text & "','" & txtLastName.Text & "','" & txtAddress.Text & "','" & cboCountry.Text & "','" & txtCompany.Text & "','" & txtNumber.Text & _
"','" & dptDateIn.Text & "','" & dptDateOut.Text & "','" & cboRoom.Text & "','" & txtNotes.Text & "')"
cmmd = New OleDbCommand(sql, cnn)
The first problem here is never NEVER NEVER use string concatenation to build your queries like that. Do it like this instead:
Dim sql As String = _
"INSERT INTO tcekin " &_
"(title,firstname,lastname,address,country,company,roomnumber,datein,dateout,rommtype,note)" &_
"VALUES(?,?,?,?,?,?,?,?,?,?,?)"
cmmd = New OleDbCommand(sql, cnn)
cmmd.Parameters.AddWithValue("Title", Combobox1.Text)
cmmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
''# ...
''# ...
This will also make it easier to spot and avoid syntax errors like the one you're complaining about.