'System.IndexOutOfRangeException' followed by 'System.Reflection.TargetInvocationException' - mysql

I always get this 2 errors when executing a query
A first chance exception of type 'System.IndexOutOfRangeException' occurred in MySql.Data.dll
Followed by
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
This is how I execute my query
Sub Get_Teller_Num(hardware_Add As String)
Check_DB_Con() 'Check if the connection is okay
SQL_Query = "SELECT teller_info.teller_num, service_info.service_num " _
& "FROM service_info " _
& "JOIN teller_info " _
& "ON service_info.service_id = teller_info.teller_id " _
& "WHERE teller_info.hardware_add = " & hardware_Add
Dim MySQL_CMD As New MySqlCommand(SQL_Query, MysqlConn)
Try
MySQL_CMD.Connection.Open()
MySQL_Reader = MySQL_CMD.ExecuteReader()
While MySQL_Reader.Read
teller_Num = MySQL_Reader("teller_info.teller_num")
service_Num = MySQL_Reader("service_info.service_num")
End While
MySQL_Reader.Close()
Catch myerror As MySqlException
Console.WriteLine("Failed to run query: " & myerror.Message)
Finally
MysqlConn.Close()
MysqlConn.Dispose()
End Try
End Sub
As you can see, I am joining another table so I can get certain values to it.

It seems that by adding ALIAS or AS in my WHERE clause and reading it based on it solves the problem.
So instead of this query:
SQL_Query = "SELECT teller_info.teller_num, service_info.service_num " _
& "FROM service_info " _
& "JOIN teller_info " _
& "ON service_info.service_id = teller_info.teller_id " _
& "WHERE teller_info.hardware_add = " & hardware_Add
Change it to (Notice that I create an ALIAS for the fields that I want to get):
SQL_Query = "SELECT teller_info.teller_num AS Teller_Num, service_info.service_num AS Service_Num " _
& "FROM service_info " _
& "JOIN teller_info " _
& "ON service_info.service_id = teller_info.teller_id " _
& "WHERE teller_info.hardware_add = " & hardware_Add
Then, we also need to change the way we read data.
Instead of this:
While MySQL_Reader.Read
teller_Num = MySQL_Reader("teller_info.teller_num")
service_Num = MySQL_Reader("service_info.service_num")
End While
Change it to (Notice that I read them based on the ALIAS that I've given to them):
While MySQL_Reader.Read
teller_Num = MySQL_Reader("Teller_Num")
service_Num = MySQL_Reader("Service_Num")
End While

Related

Acces VBA DLOOKUP

Teller = Nz(DLookup("[Teller]", "[Lookuptable]", ("Artikel = '" & ValueArtikel & "' " And " Lookuptable= 'G'")), 0)
Noemer = Nz(DLookup("[Noemer]", "[lookuptable]", ("Artikel = ' " & ValueArtikel & " ' " And Lookuptable= " 'G' ")), 0)
I want to perform a DLOOKUP in acces vba but i can't find the right statement. I looked at many sites and this are the two dlookups that i think are correct but both give the error types don't match. Teller and noemer are integers, Artikel and artikelvalue and Lookuptable are strings. Sorry if this is already asked but i can't find it. i find many posts about it but i can't fixed it. And especcialy sorry for my bad english
The first one is close. Use variables and Debug.Print to help building the strings.
Ctrl+g shows the output.
strCrit = "Artikel = '" & ValueArtikel & "' And Lookuptable= 'G'"
Debug.Print strCrit
Teller = Nz(DLookup("[Teller]", "[Lookuptable]", strCrit), 0)
I use my own function for Lookups because Lookups have a really bad performance.
' Lookups Replacements
'---------------------
Function DLook(Expression As String, Domain As String, Optional Criteria) As Variant
On Error GoTo Err_Handler
Dim strSQL As String
'DCount: strSQL = "SELECT COUNT(" & Expression & ") FROM " & Domain
'Other replacements
'DLookup:
strSQL = "SELECT " & Expression & " FROM " & Domain
'DMax: strSQL = "SELECT MAX(" & Expression & ") FROM " & Domain
'DMin: strSQL = "SELECT SUM(" & Expression & ") FROM " & Domain
'DFirst: strSQL = "SELECT FIRST(" & Expression & ") FROM " & Domain
'DLast: strSQL = "SELECT LAST(" & Expression & ") FROM " & Domain
'DSum: strSQL = "SELECT SUM(" & Expression & ") FROM " & Domain
'DAvg: strSQL = "SELECT AVG(" & Expression & ") FROM " & Domain
If Not IsMissing(Criteria) Then strSQL = strSQL & " WHERE " & Criteria
DLook = DBEngine(0)(0).OpenRecordset(strSQL, dbOpenForwardOnly)(0)
Exit Function
Err_Handler:
MsgBox "Error. Lookup couldnt be performed" & vbNewLine & Err.Description, vbCritical
End Function
Called with:
If DLook("Column2", "Table1", "Column1 = " & ID) = 0 Then
'Do stuff
End If
If DLook("Column2", "Table1") = 0 Then
'Do other stuff
End If

INSERT INTO table with Foreign Key from Form

I am trying to create a Form that is used to manually enter data in certain scenarios. Most data is input from CSV files which is working fine. I have 4 tables, Part , Assembly , MachineOrder , and Job. I was able to write code for entering into the base table, Part, from the Form no problem. The issue now is entering data into the Assembly and MachineOrder tables where the Parts are being referenced by their PID autonumber field and the Assemblies are being referenced by their AID autonumbered field. I have tried many different kinds of methods to perform this of which you can see a bit of in my commented out code. What is there is what I believe to be my closest to correct code thus far with the error now being that Access asks me for the parameter value of rPID even though it is finding the value in the Dlookup function fine. I'm assuming the same is true for the rAID section as well.
Otherwise I'm getting errors of Key Violations when using the INSERT then UPDATE method you see commented out.
The form is called HOTEntry
Any advice on what my problem may be is greatly appreciated, I'm a student and this is my first time trying to use what I've learned in a professional application so any and all constructive criticism is wanted! Apologies if this is a rather specific question but I could really use the help on this since I've been working on it for two days to no avail...
My code:
Sub HOTParts2()
Dim rPID As Integer
Dim rAID As Integer
Dim dbs As DAO.Database
Dim sqlstr1 As String
Dim sqlstr2 As String
Dim sqlstr3 As String
Dim sqlstr4 As String
Set dbs = CurrentDb
'sqlstr1 = "INSERT INTO Assembly ( PID, ModelNum, ModelRev, ModelDescription ) " _
' & "SELECT (PID,Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes)" _
' & "FROM Part " _
' & "WHERE Part.PartName = Forms!HOTEntry!txtPartName AND Part.Config = Forms!HOTEntry!txtConfigEntry AND Part.Rev = Forms!HOTEntry!txtRevEntry"
sqlstr1 = "INSERT INTO Assembly ( ModelNum, ModelRev, ModelDescription,PID ) " _
& "VALUES (Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes," & "rPID" & ");"
'
'sqlstr2 = "UPDATE Assembly " _
' & "SET PID =" & rPID & " " _
' & "WHERE Assembly.ModelNum = Forms!HOTEntry!txtHotModel And Assembly.ModelDescription = Forms!HOTEntry!txtHotDes And Assembly.ModelRev = Forms!HOTEntry!txtHotRev;"
'
'sqlstr3 = "INSERT INTO MachineOrder ( AID, Serial, CustName ) " _
' & "SELECT (AID,Forms!HOTEntry!txtHotSerial, Forms!HOTEntry!txtHotCust)" _
' & "FROM Assembly" _
' & "WHERE Assembly.Model=Forms!HOTEntry!txtHotModel And ModelDescription= Forms!HOTEntry!txtHotDes And ModelRev = Forms!HOTEntry!txtHotRev; "
sqlstr3 = "INSERT INTO MachineOrder (Serial, CustName, AID ) " _
& "VALUES (Forms!HOTEntry!txtHotSerial, Forms!HOTEntry!txtHotCust," & "rAID" & ");"
'
'sqlstr4 = "UPDATE MachineOrder " _
' & "SET AID =" & rAID & " " _
' & "WHERE AID IS NULL;"
rPID = DLookup("PID", "Part", "PartName = " & "'" & Forms!HOTEntry!txtPartName & "'" & " And " & "Config = " & "'" & Forms!HOTEntry!txtConfigEntry & "'" & " And " & "Rev = " & "'" & Forms!HOTEntry!txtRevEntry & "'")
DoCmd.RunSQL sqlstr1
'DoCmd.RunSQL sqlstr2
rAID = DLookup("AID", "Assembly", "ModelNum = " & "'" & Forms!HOTEntry!txtHotModel & "'" & " And " & "ModelDescription = " & "'" & Forms!HOTEntry!txtHotDes & "'" & " And " & "ModelRev = " & "'" & Forms!HOTEntry!txtHotRev & "'")
DoCmd.RunSQL sqlstr3
'DoCmd.RunSQL sqlstr4
End Sub
Well, if you want to use the looked up rPID and rAID in a query, you need to do more than just set them in VBA. You can either manually fill them in in your SQL statement, use a parameter and a QueryDef and fill in the parameter in your QueryDef, or put the DLookUp inside your SQL statement.
Going with the first approach here, only unquoted rPID in your initial statement, and put it after rPID was set.:
rPID = DLookup("PID", "Part", "PartName = " & "'" & Forms!HOTEntry!txtPartName & "'" & " And " & "Config = " & "'" & Forms!HOTEntry!txtConfigEntry & "'" & " And " & "Rev = " & "'" & Forms!HOTEntry!txtRevEntry & "'")
sqlstr1 = "INSERT INTO Assembly ( ModelNum, ModelRev, ModelDescription,PID ) " _
& "VALUES (Forms!HOTEntry!txtHotModel, Forms!HOTEntry!txtHotRev, Forms!HOTEntry!txtHotDes," & rPID & ");"
DoCmd.RunSQL sqlstr1

Access stored procedure not working

The following stored procedure is not working, I have tried everything without success. Help please.
Sub Create_View()
Dim conn As ADODB.Connection
Set conn = Application.CurrentProject.Connection
conn.Execute "CREATE VIEW vw_RobPS AS " & _
"SELECT sid, " & _
"Lname, " & _
"Fname, " & _
"EmpStatus, " & _
"[Peax Update as of 6-18-15], " & _
"[Peax Update Date] " & _
"FROM Master_06-18-2015" & _
"WHERE [Peax Update Date] as PeaxUdDt is not null; "
Application.RefreshDatabaseWindow
ExitHere:
If Not conn Is Nothing Then
If conn.State = adStateOpen Then conn.Close
End If
Set conn = Nothing
End Sub
When, I run it, I get this error message:
Run-time error'-2147217900(80040e14)': Syntax error in FROM clause.
I can't find the problem.
Your table name includes dashes; enclose that name in square brackets
Include a space between the table name and WHERE
Don't try to alias a field in the WHERE clause
"FROM [Master_06-18-2015] " & _
"WHERE [Peax Update Date] is not null; "

Dates are not updating through sql code in vba

I want to update serial.Issuedate getting from form but its giving syntax error.
Please help me how can I correct this error.
My code is below:
Private Sub Command30_Click()
Set serialrs = CurrentDb.OpenRecordset("serial")
Dim Idate As Date
Dim Itodo As String
Idate = Me.IssuedDate.Value
Itodo = Me.IssuedToDO.Value
Dim issueqry As String
issueqry = "UPDATE serial " _
& " set serial.IssueToDO = '" & Itodo & "'" _
& " serial.issuedate = (#" & Format(Idate, "mm\/dd\/yyyy") & "#)" _
& " WHERE (((serial.id) Between 1 And 10)) "
DoCmd.RunSQL issueqry
MsgBox ("Issued Done")
End Sub
When you update more than one field, you must include a comma between the field expressions like this ...
SET [field name] = "foo", [another field] = 17
^
here
So try your code like this ...
issueqry = "UPDATE serial " _
& " set serial.IssueToDO = '" & Itodo & "'," _
& " serial.issuedate = #" & Format(Idate, "mm/dd/yyyy") & "#" _
& " WHERE serial.id Between 1 And 10"
Also give yourself an opportunity to inspect the string the code built ...
Debug.Print issueqry
You can view the output from Debug.Print in the Immediate window. Ctrl+g will take you there.

How do I resolve this query?

I receive runtime error 3122 :
You tried to execute a query that does not include the specified expression count(*)*t2.Daily_Charge_HKD as part of the aggregate function
What I want to do in the query:
I want to group all the record in Opt_In_Customer_Record by event_plan_code, and have a total count for each of the code, then I reference the daily_charge from the daily_charge table by t1.event_plan_code = t2.event_plan_code, and multiply the daily_charge with the total count for each of the code
Here is my code:
Private Sub btnGenDaily_Click()
Dim filename As String
Dim prefix As String
Dim qryDef As DAO.QueryDef
Dim dbs As DAO.Database
Set dbs = OpenDatabase(CurrentDb.Name)
If IsNull(txtInputPath.value) Then
MsgBox "Please enter a valid input file location."
Else
If FileExists(txtInputPath.value) Then
If IsNull(txtOutputPath3.value) Then
MsgBox "Please enter a valid output file location."
Else
prefix = GetFileNamePrefix(txtInputPath.value)
sql = "select t1.event_plan_code, count(*), count(*)*t2.Daily_Charge_HKD " & _
"from Opt_In_Customer_Record t1 Inner Join Daily_Charge t2 " & _
"On (t1.event_plan_code=t2.event_plan_code and t2.Home_BMO='" & prefix & "') " & _
"group by t1.event_plan_code " & _
"order by t1.event_plan_code "
MsgBox sql
If ObjectExists("Query", "getDailyCharge") Then
DoCmd.DeleteObject acQuery, "getDailyCharge"
End If
With dbs
.QueryTimeout = 0
Set QueryDef = .CreateQueryDef("getDailyCharge", sql)
End With
strPathToSave = txtOutputPath3.value
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "getDailyCharge", strPathToSave, True
MsgBox "Daily charge report generated."
End If
Else
MsgBox "Input file does not exist. Please enter again."
End If
End If
End Sub
I know you mentioned in a comment that you don't want to group by "t2.Daily_Charge_HK", but to use that in the way you are doing with access you will need to group it, because of your join I'm guessing you only have one Daily Charge value for each event plan code so the grouping in this case won't be a problem. e.g. all event plan codes with id of 1 and Home BMO a prefix of x will have the same charge rate.
Change:
sql = "select t1.event_plan_code, count(*), count(*)*t2.Daily_Charge_HKD " & _
"from Opt_In_Customer_Record t1 Inner Join Daily_Charge t2 " & _
"On (t1.event_plan_code=t2.event_plan_code and t2.Home_BMO='" & prefix & "') " & _
"group by t1.event_plan_code " & _
"order by t1.event_plan_code "
Into:
sql = "select t1.event_plan_code, count(*), count(*)*t2.Daily_Charge_HKD " & _
"from Opt_In_Customer_Record t1 Inner Join Daily_Charge t2 " & _
"On (t1.event_plan_code=t2.event_plan_code and t2.Home_BMO='" & prefix & "') " & _
"group by t1.event_plan_code, t2.Daily_Charge_HKD " & _
"order by t1.event_plan_code, t2.Daily_Charge_HKD "
Hope this helps
Finally I come up with this solution and it works:
sql = "select t1.event_plan_code, Count, Count*Daily_Charge_HKD As 'Count * Daily_Charge_HKD' " & _
"from (select event_plan_code, count(*) As Count " & _
"from Opt_In_Customer_Record " & _
"group by event_plan_code " & _
"order by event_plan_code) t1, Daily_Charge t2 " & _
"where t1.event_plan_code=t2.event_plan_code and t2.Home_BMO='" & prefix & "' " & _
"order by t1.event_plan_code"