MySqlException was unhandled when using count on SQL query - mysql

When my SQL query has a count function in the query it does not want to display the data in the DBGRID and I'm getting a "MySqlException was unhandled" error. As soon as I remove the count function it runs smoothly and displays the data on the DB grid.
Code below:
Dim connection As New MySqlConnection("Server info")
Dim cmd As New MySqlCommand("SELECT COUNT(a.client_id), a.CLIENT_ID,b.c_name, b.C_surname FROM tblinv_info a JOIN tblclientinfo b ON a.CLIENT_ID = b.CLIENT_ID WHERE extract(year from a.inv_date) in ('2018','2019') AND a.Client_id = b.Client_id GROUP BY a.client_id ORDER BY count(a.client_id) desc LIMIT 10", connection)
cmd.CommandTimeout = 500
Dim adapter As New MySqlDataAdapter(cmd)
Dim table As New DataTable()
adapter.Fill(table)
dbreport.DataSource = table
Any idea on why this could be happening? I'm running the program in Visual Studio coding with VB.NET and using a MySql database. The SQL command runs fine on the localhost database.
Error: Error code is as follows: An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional information: Fatal error encountered attempting to read the resultset.

I hope you are well.
I think, the problem is, in the Select query, all the fields have a name column, but the counter, don't.
SELECT COUNT(a.client_id), a.CLIENT_ID,b.c_name, b.C_surname ...
And, the filler and data source don't know where to place the counter column.
Set As name to counter column.
SELECT COUNT(a.client_id) AS Counter1, a.CLIENT_ID,b.c_name, b.C_surname
adapter.Fill(table)
dbreport.DataSource = table

You have missing your fields in group by
Run this in SQL query editor
SELECT COUNT(a.client_id) as cnt, a.CLIENT_ID, b.c_name, b.C_surname -- NOTE CHANGE
FROM
tblinv_info a JOIN
tblclientinfo b ON a.CLIENT_ID = b.CLIENT_ID
WHERE
extract(year from a.inv_date) in ('2018','2019') AND
a.Client_id = b.Client_id
GROUP BY
a.client_id,
b.c_name, -- NOTE CHANGE
b.C_surname -- NOTE CHANGE
ORDER BY
cnt desc -- NOTE CHANGE
LIMIT 10

It sounds like your query timed out during execution.
You can increase command timeout using CommandTimeout.
cmd.CommandTimeout = 120; // 2 minutes (example)
Detailed code:
Dim connection As New MySqlConnection("My Server info")
Dim cmd As New MySqlCommand("SELECT COUNT(a.client_id), a.CLIENT_ID,b.c_name, b.C_surname FROM tblinv_info a JOIN tblclientinfo b ON a.CLIENT_ID = b.CLIENT_ID WHERE extract(year from a.inv_date) in ('2018','2019') AND a.Client_id = b.Client_id GROUP BY a.client_id ORDER BY count(a.client_id) desc LIMIT 10", connection)
cmd.CommandTimeout = 120
Dim adapter As New MySqlDataAdapter(cmd)
Dim table As New DataTable()
adapter.Fill(table)
dbreport.DataSource = table

Ok I finally got the problem sorted.
The mysql.data.dll file I was using as a reference (ver6.3.5.0) was too old.
I downloaded version 6.4.4.0 and removed the old reference and now it displaying perfectly.

Related

Select SQL statement from multiple database

My question has 2 parts, and i am unsure if it is my query which is causing the error or data adapter.
Part 1. I have a mySQL query which works fine on SQLyog, the query involves selection from tables existing in different databases. And both databases has been set to have the same accecss rights for the user account used at the connection string.
Below will be my query.
SELECT `portaldb`.`users`.`full_name` AS 'Name of User'
,`Systemrevamp`.`System_countries`.`CountryName` AS 'Quoted For'
,`Systemrevamp`.`uniquequote`.`UniqueQuote` AS 'System Quote ID'
, IF (
LEFT(`Systemrevamp`.`uniquequote`.`username`, 1) = ' '
,'Web Access'
,'Bulk Upload'
) AS 'Type'
,DATE_FORMAT(`Systemrevamp`.`uniquequote`.`insertedon`, '%d-%b-%Y') AS 'Quoted On'
FROM `portaldb`.`users`
INNER JOIN `Systemrevamp`.`uniquequote` ON TRIM(`Systemrevamp`.`uniquequote`.`UserName`) = `portaldb`.`users`.`usrname`
INNER JOIN `Systemrevamp`.`System_countries` ON `Systemrevamp`.`System_countries`.`Code` = `Systemrevamp`.`uniquequote`.`CountryCode`
INNER JOIN `portaldb`.`permission_details` ON `portaldb`.`permission_details`.`user_ID` = `portaldb`.`users`.`user_ID`
WHERE `portaldb`.`permission_details`.`group_ID` = '5'
AND `Systemrevamp`.`uniquequote`.`insertedon` >= (NOW() - INTERVAL 3 MONTH)
ORDER BY `portaldb`.`users`.`full_name` ASC,`Systemrevamp`.`uniquequote`.`insertedon` ASC
Visual studio keeps telling me there is syntax error and to check the version of SQL, but I am able to retrieve at the database.
Part 2. Below is a snippet of my code. My question for this part is, if the above query is used, what source table should I put for the data adapter to fill at 'XXX'?
myDataAdapter = New MySqlDataAdapter(strSQL, myConnection)
allUserDataset = New DataSet()
myDataAdapter.Fill(allUserDataset, "XXX")
gvAllQuotes.DataSource = allUserDataset
gvAllQuotes.DataBind()
Please let me know if more information is needed. Thank you.

Prepared Statement in mysql through excel VBA

I have worked on a prepared statement in Mysql, which dynamically creates week columns based on the current date. It works seamlessly when I run the query in Toad for Mysql, I'm having enormous problems running the query when I am trying to convert the query to a string in VBA......I get an error stating I have a problem with the syntax near etc with the sql. The error is created in every part of the sql despite the fact the string looks fine. I subbed in for " with chr(34), or ' with chr(39) and still I get an error with the sql syntax. I have also tried to avoid these string problems by importing the code below which imports the .sql file to no avail.
Sub TopAway()
Dim Cnn As Object
Dim Rst As Object
Dim ConnectionString, SqlTextFile, SqlStatement As String
Set Cnn = CreateObject("ADODB.Connection")
Set Rst = CreateObject("ADODB.Recordset")
Application.ScreenUpdating = False
ThisWorkbook.Sheets("Summary").Range("A2:T3000").ClearContents
ConnectionString = "Driver={MySQL ODBC 5.3 Unicode Driver};Server = 10.1.1.201; Database = cms; Uid = root; Pwd = something;"
Cnn.Open ConnectionString
Cnn.CommandTimeout = 900
SqlTextFile = "C:\Users\adam\Desktop\WORK FOLDER\Tony Project\Analysis Projects\Away_No_Stock\Dynamic_Away.sql"
Debug.Print SqlTextFile
Dim hFile As Long
hFile = FreeFile
Open SqlTextFile For Input As #hFile
SqlStatement = Input$(LOF(hFile), hFile)
Close #hFile
Debug.Print SqlStatement
Rst.Open SqlStatement, Cnn '<-- This is where the code fails
Sheets("Summary").Range("B3").CopyFromRecordset Rst
End Sub
The SQL code is below.....
SELECT
GROUP_CONCAT(DISTINCT
CONCAT("SUM(IF((part_id IN (265,302,647) OR notes REGEXP ('away|unfit|unavailable|bus away|night')) && WEEKOFYEAR(job_engineerdate) = '", WEEKOFYEAR(job_engineerdate) , "' , 1 ,0)) AS '", WEEKOFYEAR(job_engineerdate), "'")
)
INTO #answers
FROM (
SELECT DISTINCT (job_engineerdate)
FROM job j
ORDER BY (job_engineerdate) ASC
) A
WHERE job_engineerdate >= CURDATE() - INTERVAL 112 DAY AND job_engineerdate <= CURDATE();
SET #query = CONCAT("SELECT customer_name, garage_name, ", #answers, "
FROM (
SELECT c.customer_name, g.garage_name, j.id, jp.part_id, jn.notes, j.job_engineerdate
FROM job j
INNER JOIN vehicle v ON j.job_vehicleid = v.id
INNER JOIN garage g ON v.garage_id = g.id
INNER JOIN customer c ON g.customer_id = c.id
INNER JOIN fault_type ft ON j.job_fault = ft.id
INNER JOIN job_parts jp ON j.id = jp.job_id
INNER JOIN part p ON p.id = jp.part_id
INNER JOIN job_notes jn ON j.id = jn.job_id
INNER JOIN users u ON j.job_engineer = u.id
WHERE
c.customer_group IN (13) AND
j.deleted = 0
AND j.job_engineerdate >= CURDATE() - INTERVAL 112 DAY
GROUP BY
v.vehicle_fleet_number, v.id, j.id, jp.part_id, jn.id
ORDER BY customer_name, garage_name
) AS T
GROUP BY customer_name, garage_name
ORDER BY 18 DESC
LIMIT 15")
;
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
I have no idea how to get this working through excel, if anybody has any ideas, it would be very much appreciated!! I have spent a long time looking on the web for answers but have not been able to find any solutions to this problem. Thanks in advance!
I tackle also with this kind of problem how to translate an sql prepared statement in Excel (VBA), finally I went through with writing a routine in VBA to build the same sql statement as it would be build by the prepared statement.
At the end a prepared statement is a "procedure" you should have no problem translating it in a VBA code.
Hope it helps you (even if I didn't manage to write the VBA code relevant to your case)...

How to find the total rows in a database

I had a look at the other topics here on getting row numbers but couldn't fully understand them. All I need is a way of getting the total number of rows.
I have the following code that reads each row and populates a listbox, however as I want to assign that rows value to an array. I need to know the row number so I can use a 2-dimentional array, where each row data is stored separately in the array.
query = "SELECT * FROM bbs_test.test"
command = New MySqlCommand(query, Sqlconn)
reader = command.ExecuteReader
While reader.Read
arraynames = reader.GetString("data_array")
ListBox_displayarray.Items.Add(arraynames)
End While
Is there a way to get the total row number.
Please could any help
Thank you
After looking at the suggestions I have tried it out and this is how my code looks like
Sqlconn.Open()
Dim querycount As String
querycount = "SELECT count(*) FROM bbs_test.test"
command = New MySqlCommand(querycount, Sqlconn)
reader = command.ExecuteReader
While reader.Read
MessageBox.Show(reader.GetString("data_array"))
End While
The following error occurs
"An unhandled exception of type 'System.IndexOutOfRangeException' occurred in MySql.Data.dll
Additional information: Could not find specified column in results"
I checked and made sure the name of the column is data_array.
Could anyone help me please.
Use
query = "SELECT COUNT(*) FROM bbs_test.test"
This will fetch the count of total number of rows in your table
you need to run the query,
queryCount = "SELECT count(*) FROM bbs_test.test"
command = New MySqlCommand(queryCount, Sqlconn)
var totalRow = command.ExecuteScalar()
In variable totalRow , you have your no. of rows.

LINQ Generating Bad Query, Error Unknown Column (VB.NET MySQL)

I'm developing in MVC2 using VB.NET and MySQL and ran into a problem trying to convert a simple SQL query to LINQ.
SQL Query:
SELECT Location_Number, sum(Column1) as totalC1, sum(Column2) as totalC2
FROM MyTable
WHERE year = 2010 and month = 8
GROUP BY Location_Number
ORDER BY Location_Number
LINQ Query:
From r In MyTable _
Where r.Year = 2010 And r.Month = 8 _
Group r By LN = r.Location_Number Into l = Group _
Order By LN _
Select New With { _
.Location_Number = LN, _
.DepositCount = l.Sum(Function(r) r.Column1), _
.OtherCount = l.Sum(Function(r) r.Column2) _
}
The error generated is:
An error occurred while executing the command definition. See the inner exception for details.
The inner exception is:
Unknown column 'GroupBy1.K1' in 'field list'
Here is the SQL generated by LINQ:
SELECT `Project1`.`Location_Number`, `Project1`.`C1`, `Project1`.`C2`
FROM (
SELECT `GroupBy1`.`A1` AS `C1`, `GroupBy1`.`A2` AS `C2`, `GroupBy1`.`K1` AS `Location_Number`
FROM (
SELECT Sum(`Column1`) AS `A1`, Sum(`Column2`) AS `A2`
FROM `MyTable` AS `Extent1`
WHERE (`Extent1`.`Year` = #p__linq__0) AND (`Extent1`.`Month` = #p__linq__1)
GROUP BY `Extent1`.`Location_Number`
) AS `GroupBy1`
) AS `Project1`
ORDER BY `Location_Number` ASC
Looking at that query its easy to spot whats causing the error. Simply, the most inner query only returns 2 columns, while the query right above it is trying to SELECT 3, thus the Unknown Column Error. So why is this happening? What is wrong with my LINQ query?
Thank you
It is a MySQL connector bug: http://bugs.mysql.com/bug.php?id=46742
Is not fixed in last (6.3.5) version.
Good news! That bug was fixed on 6.3.7 (see comments in http://bugs.mysql.com/bug.php?id=46742).
Yes, it's a mySQL connector bug.
Try this:
Using context = New YourContext()
Dim sql = "SELECT Location_Number, sum(Column1) as totalC1, sum(Column2) as totalC2 FROM MyTable WHERE year = #YEAR and month = #MONTH GROUP BY Location_Number ORDER BY Location_Number"
Dim args = New DbParameter()
{
New SqlParameter() With {Key .ParameterName = "YEAR", Key .Value = 2010}, New SqlParameter() With {Key .ParameterName = "MONTH", Key .Value = 8}
}
Return context.ExecuteStoreQuery(Of MyTable)(sql, args).ToList()
End Using

I need the metadata from a mysql resultset, is this possible?

I'd like to obtain the metadata from the results of a mysql query so I can put it into a datatable in c#. I primarily need the column name and the data type. Here's a simple example.
show columns from (
select sum(subtotal) as subtotal
, sum(tax1+tax2+tax3+tax4) as tax
, sum(subtotal)+sum(tax1+tax2+tax3+tax4) as total
from tbltransmaster
where batchnum in (
SELECT BatchNum
FROM tblshiftmaster
WHERE ClosingTS <> -1
ORDER BY OpeningTS ASC
)
) as x
It generates this error though
Error Code : 1064 You have an error in
your SQL syntax; check the manual that
corresponds to your MySQL server
version for the right syntax to use
near '(
select sum(subtotal) as subtotal
, sum(tax1+tax2+tax3+tax4) as tax
, sum' at line 1
Could someone provide me with some advice, or perhaps a link to assist with this?
show columns only works for actual tables and views, not for queries.
Since you mention C#, you're probably using ADO.NET ? You can directly fill a DataTable which figure out the data types and column names.
DbConnection conn = null;
DbConnection conn = null;
DbCommand cmd = null;
DbDataAdapter da = null;
DataTable tbl = new DataTable();
conn = new MySqlConnection(connectionString);
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText = query;
da = new MySqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(tbl);
If you want to get the colum names only, you could fetch the result using a DataReader instead:
DbDataReader dbReader = cmd.ExecuteReader();
for (int i = 0; i < dbReader.FieldCount; i++) {
Type colType = dbReader.GetFieldType(i);
String colName = dbReader.GetName(i);
}
DbDataReader also have the .GetSchemaTable() which returns a DataTable describing the metadata of the result.