inserting an array into table via direct SQL injection - sql

There is an SQL error 3134 syntax error when trying to insert these arrays into the data table in Microsoft access 2016. I am unsure if it is due to the fact that they are arrays or if it is due to their variable types
Currently I am using the Record set method to insert into my table, however due to .Update not accepting duplicates into the table I would like to use direct SQL injection to be able to add in the data.
Dim SCR_Link_Array(), SCR_Number_Array(), SCR_Unit_Array(), SCR_EquipTag_Array(), _
SCR_SCI_Array(), SCR_Title_Array(), SCR_EquipFail_Array(), SCR_Facility_Array() As String
Dim SCR_DiscoveryDate_Array(), SCR_FileDate_Array(), SCR_OccurenceDate_Array() As Date
Dim SCR_RowCount, row, record, field As Integer
'array definition happens here
For record = 0 To SCR_RowCount - 1
'This loop is for inserting lines into the DataBase table tblimportedSCRs
insertSQL = "INSERT INTO tblimportedSCRs(SCR #, Unit, System,Event Title,SCR Date,Date Occured,Discovery Date,Eq Fail,Facility) VALUES (" & SCR_Number_Array(record) & ", " & SCR_Unit_Array(record) & ", " & SCR_SCI_Array(record) & "," & SCR_EquipTag_Array(record) & "," & SCR_Title_Array(record) & "," & SCR_FileDate_Array(record) & "," & SCR_OccurenceDate_Array(record) & "," & SCR_DiscoveryDate_Array(record) & "," & SCR_EquipFail_Array(record) & "," & SCR_Facility_Array(record) & ")"
DoCmd.RunSQL insertSQL
Debug.Print (record)
Next record
I would like this to insert properly into the table however whenever I run the DoCmd.RunSQL insertSQL the code encounters runtime error 3134.

due to .Update not accepting duplicates into the table I would like
to use direct SQL
That won't make any difference.
If duplicates are not allowed, there is - by definition - no way to circumvent this.

Related

Trying to Find Duplicate Records in Access Error

I am making a databse for a sports club,
When filling out a form, they input the facility ID, start time, end-time and date.
What I am trying to do is when they enter the end time box, the function scans through the entries on the 'Bookings' Table where all the data from this form is stored, to see if the facility is booked out at this time. ( For dtermining if it is booked out at a certain time, if the start time or the end time on table is between what is filled in on the form, an error is thrown
The code is shown below:
Private Sub EndNon_AfterUpdate()
Dim criteria As String
criteria = _
"Non-PlayingFacilityID= " & Me.NonPlayID.Value & " " & _
"Date(Non-PlayingFacility)= " & Me.DateNon.Value & _
" " & "AND [StartTime(Non-PlayingFacility)] Between Me.StartNon.Value And Me.EndNon.Value OR [EndTime(Non-PlayingFacility)] Between Me.StartNon.Value And Me.EndNon.Value "
If DCount("*", "Bookings", criteria) > 0 Then
MsgBox "Unfortunately, this facility is booked at this time"
Me.Undo
End If
End Sub
Syntax error is thrown when I run this, not sure why.
Any help would be much appreciated
It probably highlights this invalid syntax:
"Date(Non-PlayingFacility)= " & Me.DateNon.Value & _
Perhaps you mean:
"DateValue([Non-PlayingFacility])= " & Format(Me!DateNon.Value, "\#yyyy\/mm\/dd\#") & _
The remaining date comparisons need to be concatenated and formatted similarly.
Addendum - given the obscure field name:
"[Date(Non-PlayingFacility)]= " & Format(Me!DateNon.Value, "\#yyyy\/mm\/dd\#") & _
The format is needed to create a valid string expression in SQL for the date value. This is independent of a format applied for display.

Why does my SQL statement not find a match with the WHERE statement below?

I'm attempting to pull data from my MS Access database via an Excel SQL statement. It does NOT give me any errors, however it also does not pull the data I'm searching for.
If items(u, 1) is text (ex. 308-203BL), then it works perfectly.
I've tried both comparing them as text and as numerical, but neither way find any matches when items(u, 1) is 19310.
This compares it as text...
LEFT(Item," & Len(items(u, 1)) & ") = '" & items(u, 1) & "'"
this compares it as numerical...
VAL(LEFT(Item," & Len(items(u, 1))) & ") = " & items(u, 1)
I have verified that there are records in the DB that match the given criteria.
items() is an array populated from a 1 column table on the sheet by items = Range("Items").Value.
Using these two SKU's as examples, the first working, the second not, the array would be as follows. .
SKU by SKU, they're fed into the SQL as below.
With the input in the example, the output I receive is an array populated only the sales for the second item. The order I put the SKU's in the table doesn't change that result. I have tested it with multiple SKU's, and no matter how many I use, it returns the proper information, with the exception of not returning any results for any numerical SKU's.
The field for Item in the DB is a short text, which is why I used '" & items(u, 1) & "'" to convert the SKU to text when I was trying to match it as text, and Val() to convert the field to a value when trying to match it as a number. Both gave me 0 record counts in the function, but did not give me a data type error.
Below is the portion of my code which determines the SQL string, and a bit afterwords which basically stuffs it into a UDF which pulls the info from the DB and puts it into an array for me. Aside from not finding a match when items(u,1) is numerical, it works perfectly.
DBString = "SELECT Invoice, Line, Inv_Date, Sales_Order, SOLine, SO_Date, CustID, Item, Part_Description, Ship_Qty, Price, Ext_Sales FROM `" & Year(tabledate) & "-" & Format(tabledate, "mm") & "` WHERE Inv_Date BETWEEN #" & Sdate & "# AND #" & Edate & "# AND LEFT(Item," & Len(items(u, 1)) & ") = '" & items(u, 1) & "'"
SalesHolder = PullFromDB(DBString, SGMDB)
I've also tried the below code instead, to force it to compare as a number instead of text, which also doesn't give me any errors, but doesn't find a match.
DBString = "SELECT Invoice, Line, Inv_Date, Sales_Order, SOLine, SO_Date, CustID, Item, Part_Description, Ship_Qty, Price, Ext_Sales FROM `" & Year(tabledate) & "-" & Format(tabledate, "mm") & "` WHERE Inv_Date BETWEEN #" & Sdate & "# AND #" & Edate & "# AND VAL(LEFT(Item," & Len(items(u, 1))) & ") = " & items(u, 1)
SalesHolder = PullFromDB(DBString, SGMDB)
Below is the UDF itself which pulls the info from the DB. It works quite nicely.
Function PullFromDB(DBStr As String, DBLoc As String) As Variant
Dim TheDB As Recordset, DBHolder() As Variant
Set TheDB = OpenDatabase(DBLoc).OpenRecordset(DBStr)
If TheDB.RecordCount = 0 Then GoTo theexit
TheDB.MoveLast
TheDB.MoveFirst
ReDim DBHolder(0 To TheDB.RecordCount, 1 To TheDB.Fields.Count) As Variant
For k = 1 To UBound(DBHolder, 2)
TheDB.MoveFirst
For j = 0 To UBound(DBHolder)
If j = 0 Then
DBHolder(j, k) = TheDB.Fields(k - 1).Name
Else
DBHolder(j, k) = TheDB.Fields(k - 1).Value
TheDB.MoveNext
End If
Next j
Next k
theexit:
TheDB.Close
Set TheDB = Nothing
PullFromDB = DBHolder
On Error GoTo -1
End Function
The expected result is to populate the array SalesHolder with the information that matches the criteria.
What am I missing? I'm going blind trying to find it.
Thank you all for your responses to this, it turns out I was completely hunting for the wrong problem. The code I posted was actually correct, the issue was with the format of Inv_Date field in the DB. I had mistakenly entered the last couple of months as text instead of date, so the WHERE Inv_Date BETWEEN #" & Sdate & "# AND #" & Edate & "# portion of my SQL didn't match anything.
I hadn't identified that this was the issue earlier due to the timing of the sales of the SKU's themselves, which was purely coincidence. When I expanded the dates range, I found that it did return results for the numerical SKU, but both numerical and text SKU's cut off two months ago.
Thank you again!

IF AND Formula in VBA Code

Recently you guys helped me solve looping through a pivot table by inserting a dynamic formula next to a pivot table and auto filling down.
'formula
frml = "=if(" & myrange.Address(0, 0) & ">0.3%," & myrange2.Address(0, 0) & ","""")"
'where i want the formula to go
pt.ColumnRange.End(xlToRight).Offset(1, 0).End(xlToLeft).Offset(1, 1).formula = frml
ActiveSheet.range("P7:P36588").FillDown
I've tried updating this formula by adding
"=if(and("
and then also adding in another range. Problem is the additional ( never shows up. I've also tried just adding "(" as it's own part but then the next part (the 'where the formula goes) stops working which makes no sense to me.
Can someone help me convert this formula into an ifand statement and also explain why the 'where the formula should go' part all of the sudden stops working?
Edit:
In total, the new addition would look like this:
"if(and(" & myrange.address(0,0) & ">0.3%," & myrange3.address(0,0) & ">$100," & myrange2.address(0,0) & ","""")
to output this formula in the corresponding cell by the pivot table
=if(and(c3>.3%,d3>$100),a3,""
the problem right now is adding that and part to the formula which would be d3. If those 2 statements work, then it should bring out a3, if not it will return nothing.
A couple of notes:
#Jeeped already answered the reason to your error - you need to add closing bracket ) to your AND.
I like to use Chr(34) to write down " inside formula strings.
I like to avoid comparing the formats inside the cell, just the values. So instead of myrange.address(0,0) & ">0.3%" I like using myrange.address(0,0) & ">0.003".
Code
frml = "=IF(AND(" & myrange.Address(0, 0) & ">0.003," & myrange3.Address(0, 0) & ">100)," & myrange2.Address(0, 0) & "," & Chr(34) & Chr(34) & ")"
You aren't closing off the AND clause with a ).
'formula
frml = "=if(and(" & myrange.address(0,0) & ">0.3%, " & myrange3.address(0,0) & ">$100), " & myrange2.address(0,0) & ", text(,))
text(,) is a good substitute for """" in a quoted string formula.

Insert list of pictures from datatable into MS Access database, VB.NET

I have a datatable containing several records. Each row of the datatable has a field that stores picture. When I loop through the datatable rows to insert them into a table of a database, every field of the row is saved correctly; but for every record, the picture in the first row of the datatable is saved. I traced the code and it does hit the lines that access and try to save the pictures in each row of the datatable. I am using VB.NET and the database is MS Access.
My code looks like this:
For Each dr As DataRow In dt.Rows
cmd.CommandText = "INSERT INTO Table1 (" & _
"[ID], " & _
"[Name], " & _
"[BDate], " & _
…….
"[TelNo], " & _
"[Photo]) " & _
" VALUES(" & _
dr("ID") & ", '" & _
dr("Name") & "', " & _
dr("BDate") & ", '" & _
…….
dr("TelNo") & "', " & _
img & ")"
cmd.Parameters.Add(img, OleDb.OleDbType.Binary).Value = dr("Photo")
cmd.ExecuteNonQuery()
Next
The code does exactly what you ask:
In your loop, all fields are varying following the values in your dataset row because you do this for each : dr(thefield)
except for the image because you just do this : img
It is thus always the same image.
You should have something like dr(image) (but I doubt it work as simply)
I find the answer myself. The problem is rather subtle. In OleDbCommands, parameters are not named. Parameters are represented by ? (the question mark). In the code snippet of my question, the variable img has the value of ?, which is assigned by a statement before the loop. The value of parameters MUST be provided in the order of their appearance. I my case, there is only one parameter and I provide a single parameter by the statement:
cmd.Parameters.Add(img, OleDb.OleDbType.Binary).Value = dr("Photo")
However, in each iteration of the loop, another parameter will be added. For the second record, the actual value of the parameter will be the second parameter , the third record will have its value at the third place, etc. Since in OleDbCommands values for parameters are identified by their order, and since there is only one parameter in my case, the picture provided first (i.e. that of the first record) is always used.
Hence the question boils down to ‘How can I provide a single parameter in each iteration?’ And the answer is to remove the parameter added by each iteration by including this precious statement:
cmd.Parameters.Clear()
as the last statement in the loop.
Sorry for the lengthy explanation.

Using RecordsAffected-method in VBA causes error when the number exceeds approximately 90.000 records?

I'm running an append-query in VBA (inside MS Access) that looks like the code below.
When I use the RecordsAffected-method in VBA in order to keep track of how many records that have been inserted, it causes an error when the number exceeds approximately 90.000 records and above? (some kind of stackoverflow error it says)
The funny part is, that when I don't use RecordsAffected-method, the query works just fine. And it also works fine when the number of rows affected is below 90.000.
What can be wrong? Is this a bug in VBA?
.
.
Dim dbs As DAO.Database
sql As String
iCount As Integer
Set dbs = CurrentDb
sql = "INSERT INTO " & ReceiveTable_selected & " SELECT " & NavisionTable_selected & ".* " & _
"FROM " & NavisionTable_selected & " " & _
"WHERE ((([" & NavisionTable_selected & "].[Entry No_] ) >" &
Counter_selected & "))"
dbs.Execute sql, dbFailOnError
iCount = dbs.RecordsAffected
Change Dim iCount As Integer to Dim iCount As Long
From the help file:
Integer variables are stored as 16-bit (2-byte) numbers ranging in
value from -32,768 to 32,767.
and:
Long (long integer) variables are
stored as signed 32-bit (4-byte)
numbers ranging in value from
-2,147,483,648 to 2,147,483,647.