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.
Related
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.
I need to make a query in a MySQL database returning records with the current date.
I found the command below and it works perfectly inside MySQL:
SELECT * FROM TBAvaliacoes WHERE DataHora = (Date_Format(Now(),'%Y-%m-%d'))
But when I do this inside ASP, it returns me the error below:
See how I am doing:
' ## LISTA RAMAIS
Set cmdListaAvaliacoes = Server.CreateObject("ADODB.Command")
cmdListaAvaliacoes.ActiveConnection = conn
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes WHERE DataHora = (Date_Format("&Now()&",'%Y-%m-%d'))"
response.write cmdListaAvaliacoes.CommandText
cmdListaAvaliacoes.CommandType = 1
Set rsListaAvaliacoes = Server.CreateObject("ADODB.Recordset")
rsListaAvaliacoes.Open cmdListaAvaliacoes, , 3, 3
If I enclose Now () in single quotation marks, it gives no error, but returns nothing.
Does anyone know how to get around this?
Awaiting,
If you want to call the Now() function defined by MySql then you shouldn't use the VB.NET function and concatenate its output to your sql. Just write the code exactly how you write it in the MySql Workbench
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = (Date_Format(Now(),'%Y-%m-%d'))"
If you want to pass a particular date then you need to format your date as expected by MySql
Dim myDate As DateTime = new DateTime(2019,8,10)
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = '" & myDate.ToString("yyyy-MM-dd") & "'"
But in this case the better approach is to use parameters (even if you have full control of what your date is)
Dim myDate As DateTime = new DateTime(2019,8,10)
cmdListaAvaliacoes.CommandText = "SELECT * FROM TBAvaliacoes
WHERE DataHora = #dat"
Dim prm = cmdListaAvaliacoes.CreateParameter("#dat", adDBDate, adParamInput)
prm.Value = myDate
cmdListaAvaliacoes.parameters.Append prm
Side note
A lot of time has passed from the last time I have used ADODB. So the parameter solution is how I remember it. Search on the net for more complete CreateParameter examples
conn = DriverManager.getConnection(connURL);
String sqlStr = "Select * from inventory where functions" + "like ? order by brand, model";
PreparedStatement pstmt = conn.prepareStatement(sqlStr);
pstmt.setString(1, "%" + search + "%");
ResultSet rs = pstmt.executeQuery();
Hi guys, i am having error with this code at line 2 and line 4. I believe that my coding contains errors.
I have a doubt that my SQL query is not correctly formatted. The pstmt.setString will set the search value to the ? in the SQL query.
The error:
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 ''%null%' order by brand, model' at line 1
The syntax of your sql query declaration is wrong. That is why you're getting that error. Why are you including + in between ?
Try
conn = DriverManager.getConnection(connURL);//this is bad use a connection pool
StringBuilder sb = new StringBuilder().append("Select * from inventory where functions");
sb.append(" like ? order by brand, model");
String sqlStr = sb.toString().intern();//use intern if this function is used many times
I need to call from a asp page a stored procedure I have in SQL 2008 and pass to it two values and at the end return the count of two variables.
this is the stored procedure I have:
/****** STUDATATAB******/
CREATE PROCEDURE StdntReconcileDups #NewSTDNT int = NULL, #OldSTDNT int = NULL output
AS
--use ZLDP01RD;
--count = 9 rows
Select count (*) from STUDATA.dbo.STUDATATAB
where STDNT = #NewSTDNT;
-- count = 576 rows
select count(*) from STUDATA.dbo.STUDATATAB
where STDNT = #OldSTDNT;
-- select duplicate keys with new student# count = 3 rows
select a.STDNT,a.crs,a.CRS_VRSN,a.QSTN,a.SCR
from STUDATA.dbo.STUDATATABa, STUDATA.dbo.STUDATATABb
where a.STDNT = #NewSTDNT
and b.STDNT = #OldSTDNT
and a.crs = b.crs
and a.CRS_VRSN=b.CRS_VRSN
and a.QSTN=b.QSTN
and a.SCR=b.SCR
-- select duplicate keys with new student# count = 3 rows
select count (*)
from STUDATA.dbo.STUDATATABa
where exists (select 1 from STUDATA.dbo.STUDATATABb
where a.STDNT = #NewSTDNT
and b.STDNT = #OldSTDNT
and a.crs = b.crs
and a.CRS_VRSN=b.CRS_VRSN
and a.QSTN=b.QSTN
and a.SCR=b.SCR );
-- delete duplicate keys with new student# 3 rows deleted
WITH STUDENT_CTE
AS
(select a.*
from STUDATA.dbo.STUDATATABa
where exists (select 1 from STUDATA.dbo.STUDATATABb
where a.STDNT = #NewSTDNT
and b.STDNT = #OldSTDNT
and a.crs = b.crs
and a.CRS_VRSN=b.CRS_VRSN
and a.QSTN=b.QSTN
and a.SCR=b.SCR ))
delete from STUDENT_CTE;
--Convert student #10826 history records to student #123196, should update 579 rows
UPDATE STUDATA.dbo.STUDATATAB
SET STDNT = #NewSTDNT, LSTUPDT_USER_ID_CD = 'DFERN', LSTUPDT_TS = getDate()
where STDNT = #OldSTDNT;
-- count= 582
select count(*) from STUDATA.dbo.STUDATATAB
where STDNT = #NewSTDNT;
-- count= 0
Select count(*) from STUDATA.dbo.STUDATATAB
where STDNT = #OldSTDNT;
go
I want to insert the code in the if argument so it calls StdntReconcileDups and pass to it the values of KeepSTDNT and RemoveSTDNT
Dim DBConn ' Connection object
If Request.Form("Action") = "Go!" then
Endif
If I got your meaning...then do like below:
SqlConnection con = new SqlConnection("Data Source= ; initial catalog= Northwind ; User Id= ; Password= '");
con.open();
After creating SqlConnection you will create Storedprocedure like below:
CREATE PROCEDURE RegionUpdate (#RegionID INTEGER,#RegionDescription NCHAR(50)) AS
SET NOCOUNT OFF
UPDATE Region
SET RegionDescription = #RegionDescription
Create a SqlCommand object with the parameters as the name of the stored procedure that is to be executed and the connection object con to which the command is to be sent for execution.
SqlCommand command = new SqlCommand("RegionUpdate",con);
Change the command objects CommandType property to stored procedure.
command.CommandType = CommandType.StoredProcedure;
Add the parameters to the command object using the Parameters collection and the SqlParameter class.
command.Parameters.Add(new SqlParameter("#RegionID",SqlDbType.Int,0,"RegionID"));
command.Parameters.Add(new SqlParameter("#RegionDescription",SqlDbType.NChar,50,"RegionDescription"));
Specify the values of the parameters using the Value property of the parameters
command.Parameters[0].Value=4;
command.Parameters[1].Value="SouthEast";
Excecute the stored procedure using the ExecuteNonQuery method which returns the number of rows effected by the stored procedure.
int i=command.ExecuteNonQuery();
The code above is the right way...You can replace #KeepSTDNT and #RemoveSTDNT exactly instead of #RegionID and #RegionDescription...I have used it myself...if you wanna more help...tell then
the concept is the exeute your request ... you will get back a recordset which you will iterate over until you get to eof... then you will call next recordset to get to the next result.
... are you looking for something like this?
connectstring = "..."
sql = "StdntReconcileDups '" & NewSTDNT & "','" & OldSTDNT & "'"
set rs = Server.CreateObject("ADODB.RecordSet")
rs.Open sql, connectstring, 3
I am using the below query to run an sql statement. It works fine. I wish to know how I can modify the query to select by a date which the user enters in ASP.NET. This means that I need to modify the part:
WHERE TRANSACTION_DATE = '02-AUG-2006'
Any ideas please?
The query I am using is this:
INSERT INTO TRANSACTION (TRX_UNIT, TRX_DATE, TRX_USR)
SELECT SOURCE_SYSTEM_CHANNEL_CODE, TRANSACTION_DATE, USER_CODE
FROM FCR_TRANSACTION
WHERE TRANSACTION_DATE = '02-AUG-2006'
What about:
// Create a connection object and data adapter
MySqlConnection cnx = new MySqlConnection(connectionString);
// Create a SQL command object
string cmdText = "INSERT INTO TRANSACTION (TRX_UNIT, TRX, TRX_USR) ";
cmdText += "SELECT SOURCE_SYSTEM_CHANNEL_CODE, TRANSACTION_DATE, USER_CODE ";
cmdText += "FROM FCR_TRANSACTION ";
cmdText += "WHERE TRANSACTION_DATE = #TransactionDate";
MySqlCommand cmd = new MySqlCommand(cmdText, cnx);
cmd .Parameters.Add("#TransactionDate", YourDate); // <-- Insert date here
// Set the command type to text
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
you must have a name for the date field where the user enters a date. let us say you decide to name it 'datename'
after that the $_POST("datename") returns the text entered in the field.
so now the WHERE statement becomes
WHERE TRANSACTION_DATE = '$_POST("datename")'
if that doesnt work, try
WHERE TRANSACTION_DATE = $_POST("datename")
all this is assuming you kept method of form transfer as POST....if you have it as GET, simply replace $_POST with $_GET here..
This should work. If it doesnt, my apologies.
If you really want to query by the exact Date, you have to validate the Userinput, and add a parameter
to the query (this is only pseudocode) :
string userInput = txtDate.Text;
DateTime parsedDate;
if (DateTime.TryParse(userInput, out parsedDate)) {
// valid date, add a Parameter to your command
var cmd = ... // create your DB Command here
cmd.CommandText = "SELECT .... WHERE Transaction_Date = #txDate";
cmd .Parameters.Add("#txDate", parsedDate);
// execute your command ...
}