How to get dataset from MySql Query using variables - mysql

I have a query like this:
SET #a = (SELECT GROUP_CONCAT(Id) FROM MyTable1 WHERE Id < 10);
SELECT * FROM MyTable2 WHERE find_in_set(IdLite, #a);
SELECT * FROM MyTable3 WHERE find_in_set(IdLite, #a);
SELECT * FROM MyTable4 WHERE find_in_set(IdLite, #a);
I've tryed to use this code to get resut:
Using ds As DataSet = MySqlHelper.ExecuteDataset(CnStr, SqlStr)
but I get error:
Fatal error encountered during command execution.
Error message is:
Parameter '#a' must be defined.
I've also tryed:
SELECT * FROM MyTable2 WHERE find_in_set(IdLite,
#a := (SELECT GROUP_CONCAT(Id) FROM MyTable1 WHERE Id < 10));
SELECT * FROM MyTable3 WHERE find_in_set(IdLite, #a);
SELECT * FROM MyTable4 WHERE find_in_set(IdLite, #a);
but I get the same error.
What's the correct way to get result into a DataSet?

DataSet mydataset = new DataSet();
MySqlConnection myConnection = new MySqlConnection();
myConnection.ConnectionString = "************";
myConnection.Open();
string mySelectQuery = "SELECT * FROM table";
MySqlCommand myCommand = new MySqlCommand(mySelectQuery,myConnection);
MySqlDataAdapter adapter = new MySqlDataAdapter(myCommand);
adapter.Fill(mydataset, "table");
dataGridView1.DataSource = mydataset;
dataGridView1.DataMember = "table";
myConnection.Close();
You can have a look in the following links:
http://forums.codeguru.com/showthread.php?448008-How-do-i-load-mysql-data-into-a-dataset-then-into-a-datagrid
http://www.dotnetheaven.com/article/how-to-load-data-from-database-into-datagridview-in-vb.net
If my answer is correct then please masrk as correct. Thank you

The error is in the connection string.
The solution is to add ;Allow User Variables=True to the database name.
This way:
CnStr = "datasource=" + Server_Name + _
";username= " + UserDB + _
";password=" + Password + _
";database=" + Database_Name + ";Allow User Variables=True"

Related

Query by date with ASP and MySQL

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

Execute query with #parameter that is autodefined and not neccesary to pass with Parameters.AddWithValue

VB.NET ask por #rownum1 definition executing this query:
qry = "SELECT #rownum1:=#rownum1+1 AS rownum, fld1, fld1 FROM ( SELECT #rownum1:=0 ) r, tablename WHERE fld2='some_value' ORDER BY fld2"
but I define it with
cmd.Parameters.AddWithValue("#rownum1", 0)
and MySQL replace #rownum1 with 0.
I tried declaring #rownum1 in the query and not using AddWithValue, but it doesn´t work:
qry = "SET #rownum1:=0; SELECT #rownum1:=#rownum1+1 AS rownum, fld1, fld1 FROM ( SELECT #rownum1:=0 ) r, tablename WHERE fld2='some_value' ORDER BY fld2"
Here is my code:
qry = "SELE...."
Dim cmd As New MySqlCommand(qry, conbd)
cmd.Parameters.AddWithValue("#rownum1", 0)
Dim dr As MySqlDataReader = cmd.ExecuteReader
Don't use AddWithValue if you don't want to provide a value. Don't use it at all, but that's a different conversation. If you want to add a parameter then call Add. If the purpose of the parameter is to pass a value out then set the Direction as well, because the default is Input.
The solution is to add Allow User Variables=True in the connection string.

Hibernate Native Query fails but SQL Query works

I have this query using hibernate:
#Query(value = "BEGIN SET #rank = 1; CREATE TEMPORARY TABLE IF NOT EXISTS results "
+ "SELECT User.userId, User.username, #rank FROM User WHERE User.username = :searchString ;"
+ "SET #rank = 2; INSERT INTO results (SELECT User.userId, User.username, #rank FROM Following "
+ "JOIN User ON Following.followsId = User.userId " + "JOIN UserProfile ON UserProfile.userProfileId = User.userProfileId "
+ "WHERE Following.userId = :userId AND User.username LIKE :searchString "
+ "ORDER BY UserProfile.followsCount DESC); "
+ "SET #rank = 3; INSERT INTO results (SELECT User.userId, User.username, #rank FROM User "
+ "JOIN UserProfile ON UserProfile.userProfileId = User.userProfileId "
+ "WHERE User.username LIKE :searchString ORDER BY UserProfile.followsCount DESC); "
+ "SELECT User.* FROM results JOIN User ON User.userId = results.userId ORDER BY #rank DESC LIMIT 50; "
+ "DROP TEMPORARY TABLE results; END;", nativeQuery = true)
List<User> findLike(#Param("searchString") String searchString, #Param("userId") Long userId);
When I run it, i'm told that it could not extract the result set (by JUNIT) and in the console
16:32:24.554 [main] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - 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 'SET #rank = 1; CREATE TEMPORARY TABLE IF NOT EXISTS results SELECT User.userId, ' at line 1
I turned hibernate.show_sql=true and even ran the query that was logged to the console using mysqlworkbench and it works.
Note that this query is running in a interface that is defined as such:
public interface IUserJpaDao extends JpaRepository<User, Long>, JpaSpecificationExecutor<User>
Any ideas why it works in MySqlWorkbench and not in hibernate?

MySQL/VB.NET(Winform) - How to use correctly #var?

I am developing a sequence in MySQL & VB.NET in which, when deleting a record, the number that identifies it, is deleted and put a sequence of 1 to 'n', the sequence is as follows.
this is the instruccion for MySQL.
SET #rownum=0;
UPDATE id_line t, (SELECT #rownum:=#rownum+1 rownum, id_line.* FROM id_line WHERE id_line.line_name=59999 and id_line.line_no<>0) r
SET t.line_no = r.rownum
WHERE (t.id_line_b = r.id_line_b)
in VB.net I use this
cmdB = New MySqlCommand("SET #rownum=0 UPDATE id_line t, (SELECT #rownum=:#rownum+1 rownum, id_line.* FROM id_line WHERE id_line.line_name='" & TextBox1.Text & "' and id_line.line_no<>0) r ) SET t.line_no = r.rownum WHERE(t.id_line_b = r.id_line_b)", conn)
but VB sends this 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 'UPDATE id_line t, (SELECT #rownum=:#rownum+1 rownum, id_line.* FROM id_lin' at line 1
Could you help me please in this error?
Updated 1:
This is my string connection.
Public conString As String = "Data Source=server_one;port=3306;Initial Catalog=test_db;User Id=root;password=root;Allow User Variables=True"
other better way for
create mysql procedure for delete mysql data query
https://www.tutorialspoint.com/What-is-stored-procedure-and-how-can-we-create-MySQL-stored-procedures
I found the error, a parenthesis, it was misplaced, this is the correct code.
cmdB = New MySqlCommand("SET #rownum:=0; UPDATE id_line t, (SELECT #rownum:=#rownum+1 rownum, id_line.* FROM id_line WHERE id_line.line_name='" & TextBox1.Text & "' and id_line.line_no<>0) r SET t.line_no = r.rownum WHERE(t.id_line_b = r.id_line_b)", conn)
Thank you everyone for your attention and support.
Regards.

Run-time error '3065' Cannot execute a select query

I have written lots of the queries but I'm struggling with this one.
I get the run-time error 3065 when I run the following sql.
Dim db As DAO.Database
Dim sqlstring As String
Set db = DBEngine(0).Databases(0)
sqlstring = "SELECT ebk.hr_leav_amnt AS hr_clia_hour, ebk.hr_leav_type, ebk.hr_leav_code, ebk.hr_empl_code, ebk.hr_loadg_amt AS hr_loadg_amt, 'Leave Pay' AS hr_provision, mst.hr_paym_code, mst.hr_base_hour, '' AS hr_splt_accr, mst.hr_leav_abbr, ype.hr_norm_pcnt, ype.hr_allw_amnt"
sqlstring = sqlstring + " FROM hrtlvebk AS ebk, hrtlvmst AS mst, hrtptype AS ype"
sqlstring = sqlstring + " WHERE ebk.hr_leav_code Like 'a%' And ebk.hr_leav_code = [mst].[hr_leav_code] And ebk.hr_leav_type Like '1%' And bk.hr_leav_type = [mst].[hr_leav_type] And ebk.hr_recd_type = 'a' And ebk.hr_lbkg_refn = 'ACCRUAL' And ebk.hr_from_dati >= 20140701 And ebk.hr_from_dati <= 20140730 And mst.hr_load_rule <> 'y' And mst.hr_paym_code = [ype].[hr_paym_code]"
sqlstring = sqlstring + " GROUP BY ebk.hr_leav_amnt, ebk.hr_leav_type, ebk.hr_leav_code, ebk.hr_empl_code, ebk.hr_loadg_amt, mst.hr_paym_code, mst.hr_base_hour, mst.hr_leav_abbr, ype.hr_norm_pcnt, ype.hr_allw_amnt"
db.Execute sqlstring, dbFailOnError
When I run statement with Query (SQL) it works fine. The only thing I change is the text in the where clause.. ('a%' - Query it is "a%")
Thank you in advance.
John
The message is true for SELECT queries you should use Openrecordset to be able to retrieve results of selection. Execute is for 'command' queries that don't return values.