Adding string as a part of query in jdbcTemplate call in MySQL - mysql

I have a query and a few parameters as follows,
String query = "SELECT * FROM table_name ORDER BY ? LIMIT ? ";
//I am creating this 'sortString' on runtime based on some user inputs
String sortString = " column1 ASC, column 2 ASC ";
int count =5;
I am calling the jdbcTemplate method as follows,
List<Map<String, Object>> rows = getJdbcTemplate().queryForList(query, sortString, count);
The query that is actually used by the jdbcTemplate is as follows,
SELECT * FROM table_name ORDER BY ' column1 ASC, column 2 ASC ' LIMIT 5
Now, the ORDER BY clause does not works since the criteria is put up inside ' ' by jdbcTemplate. How can I add the string to the query without the jdbcTemplate adding the " ' " by default.
I want the query to be,
SELECT * FROM table_name ORDER BY column1 ASC, column 2 ASC LIMIT 5

You cannot use a prepared statement, when you generate a whole part of the query dynamically. The ? in a prepared statement always stands for a value.
//I am creating this 'sortString'
String sortString = " column1 ASC, column 2 ASC ";
String query = "SELECT * FROM table_name ORDER By " + sortString + " LIMIT ? ";

Related

Concat a string to a field value into a table

I want to add a string i.e "Building " to each random name of my table.
I tried concat, & and +
UPDATE officine
SET nom = (SELECT fake_name.last_name
FROM fake_name
ORDER BY rand()
LIMIT 1);
I have actually :
Dupont
March
and I would like to get
Building Dupont
Building March
Something like this?
UPDATE officine
SET nom = (SELECT CONCAT('Building ', fake_name.last_name)
FROM fake_name
ORDER BY rand()
LIMIT 1
);

MySQL condition depending on column value

So, I have more or less this structure of columns in my table:
Name Age Operator
---- --- --------
Jhon 35 >
Michael 30 =
Jess 27 <
Based on that I want to make a query like this
SELECT * FROM mytable WHERE Name = 'John' AND Age > 40
obviosly this will return no results, and thats fine, but my problem is that I want to use Jhon's "Operator" value (> in this case) to make that condition.
Is it possible?
Thank you!
You can simply do it like this:
SELECT
*
FROM Table1
WHERE Name = 'Jhon'AND CASE
WHEN Operator = '>' THEN Age > 10
WHEN Operator = '<' THEN Age < 10
WHEN Operator = '=' THEN Age = 10
END
see it working live in an sqlfiddle
You also could use MySQL's PREPARE and EXECUTE statements to make dynamic SQL.
SET #name = 'Jhon';
SET #operator = NULL;
SET #age = 10;
SELECT
Operator
INTO
#operator
FROM
Table1
WHERE
Name = #name;
SET #SQL = CONCAT(
"SELECT"
, " * "
, " FROM "
, " Table1 "
, " WHERE "
, " name = '", #name, "' AND age ", #operator, ' ' , #age
);
SELECT #SQL; # not needed but you can see the generated SQL code which will be executed
PREPARE s FROM #SQL;
EXECUTE s;
see demo https://www.db-fiddle.com/f/3Z59Lxaoy1ZXC4kdNCtpsr/1

how to use datetimepicker on Delphi 7

How to use TDateTimePicker with time format (hour:minute:second)?
I tried this code:
Sql.text:= ('select * from namatabel where namafield between '+quotedstr(formatdatetime('yyyy/mm/dd', datetimepicker1.date))+' and '+quotedstr(formatdatetime('yyyy/mm/dd', datetimepicker2.date))+' and field order by field ASC');
Also this code:
Sql.text:= ('select * from tablename where fieldname between '+quotedstr(formatdatetime('yyyy/mm/dd hh:mm:ss', datetimepicker1.date))+' and '+quotedstr(formatdatetime('yyyy/mm/dd hh:mm:ss', datetimepicker2.date))+' and fieldname order by fieldname ASC');
Also this code:
Sql.text:= ('select * from tablename where fieldname between '+quotedstr(formatdatetime('yyyy/mm/dd hh:mm:ss', datetimepicker1.datetime))+' and '+quotedstr(formatdatetime('yyyy/mm/dd hh:mm:ss', datetimepicker2.datetime))+' and fieldname order by fieldname ASC');
but those wont work, help me to correct them.
I'm using SQLYog against a MySQL database.
UPDATE
#Jens Borrisholt i try this code before, but it doesnt work either
SQL.Add('SELECT meteran.kd_meter as no,kamar.nama,meteran.waktu,meteran.meter '+
'FROM meteran,kamar WHERE kamar.idkamar = meteran.idkamar AND meteran.waktu BETWEEN :tgl1 and :tgl2 and waktu group by waktu asc');
ParamByName('tgl1').AsString:=FormatDateTime('yyyy-mm-dd',DateTimePicker1.DateTime);
ParamByName('tgl2').AsString:=FormatDateTime('yyyy-mm-dd',DateTimePicker2.DateTime); end;
DBGrid2.DataSource.DataSet:=MyQuery2;
Your query is wrong
and fieldname is too much
shortened with data
NOT OK
Sql.text:= 'select * from tablename where fieldname between "2006-06-11"'+
'and "2006-06-19" and fieldname order by fieldname ASC';
OK
Sql.text:= 'select * from tablename where fieldname between "2006-06-11" '+
'and "2006-06-19" order by fieldname ASC';
example valid SQL with data
select * from auktionen where auktionende between '2006-06-11' and '2006-06-19' order by auktionende ASC;
All together with your code. without and waktu
BETWEEN :tgl1 and :tgl2 and waktu
MyQuery2.Close;
MyQuery2.SQL.Text := 'SELECT meteran.kd_meter as no,kamar.nama,meteran.waktu,meteran.meter '+
'FROM meteran,kamar WHERE kamar.idkamar = meteran.idkamar'+
' AND meteran.waktu BETWEEN :tgl1 and :tgl2'+
' group by waktu';
MyQuery2.ParamByName('tgl1').AsString:=FormatDateTime('yyyy-mm-dd',DateTimePicker1.Date);
MyQuery2.ParamByName('tgl2').AsString:=FormatDateTime('yyyy-mm-dd',DateTimePicker2.Date);
DBGrid2.DataSource := DataSource1;
MyQuery2.Open;
I mt sure what is your exact requirement.ill try to help you.
I)If you want to compare the date of the datetimepicker against a date of datetime field in table,
SQL.Add(format('select * from tablename where cast ([my_date_time_var] as date) between %s and %s ' ,[Quotedstr(FormatDateTime('MM/DD/YYYY',(datepicker1.Date))),Quotedstr(FormatDateTime('MM/DD/YYYY',(datepicker2.Date)))]))
II)If you want to compare the date time of the datetimepicker against a date time of datetime field in the table,
SQL.Add(format('select * from tablename where my_date_time_var between %s and %s ' ,[Quotedstr(FormatDateTime('MM/DD/YYYY HH:MM:SS',(datepicker1.DateTime))),Quotedstr(FormatDateTime('MM/DD/YYYY HH:MM:SS',(datepicker2.DateTime)))]));
III)If you want to compare the time of the datetimepicker against a time of datetime field in table,
SQL.Add(format('select * from tablename where cast ([my_date_time_var] as time) between %s and %s ' ,[Quotedstr(FormatDateTime('HH:MM:SS',(datepicker1.time))),Quotedstr(FormatDateTime('HH:MM:SS',(datepicker2.Time)))]))
Please let me know if your requirement is not the same

MySqlDataReader reads data when there is sum(a+b) in the query

When I use this query
("SELECT id, at_date AS MyDate , nom, pax, SUM(prix*pax) AS somme,
SUM(pax) AS totpax
FROM atelier ORDER BY " + Order_by + " " + SortDir + " LIMIT #Myid," +
PublicVariables.MySqlLimit, conn)
This gives an error here
_listBox[1].Items.Add(Convert.ToDateTime(reader["MyDate"]).ToString("d"));
Because there is NO ROWS int the table. Table is EMPTY.
But when I supress SUM(prix*pax) AS somme and SUM(pax) AS totpax from the query, reader does not read and no error occurs.
Is there any trick of MySql in there ?
I resolved the probleme by checking the table if there is any rows before calling this method but it's not what I like any idea ?
Use Group by clause for all non aggregate function before order by clause:
group by id,MyDate,nom,pax

Delete query error for multiple records

I have a problem in this query:
string sqlString = "DELETE FROM [upload_news] WHERE (SELECT TOP " + no_of_recordss + " * FROM [upload_news] WHERE [country]='" + countryy.Text + "')";
Error Message :
Error: {"An expression of non-boolean type specified in a context
where a condition is expected, near ')'."}
How can i fix this ?
In the where clause you need a boolean expression.
Moreover, mysql doesn't support select top, you have to use limit instead and you can use it directly on delete
So your query should be:
delete from upload_news
where country=<SOME_COUNTRY> limit <NO_OF_RECORDS>
You have to replace values within "<>" with your desired values.
Or in your "strange" syntax:
string sqlString = "DELETE FROM [upload_news] WHERE [country]='" + countryy.Text + "' limit "+no_of_recordss;