how to use query result in java - java

I wrote this query in java that gives me the list of tables and save them in data collection:
sql = "select * FROM information_schema.tables WHERE table_type = 'BASE TABLE'";
ResultSet rs = stmt.executeQuery(sql);
int count_table = 0;
while (rs.next()) {
table_list.add(rs.getString(3));
count_table += 1;
}
Table_list = table_list.toString();
Table_list is string.
But when i want to use this list in another query in this way:
sql="SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + Table_list[t] + "'";
Gives me this error :
array required, but java.lang.String found
I used this in c# and worked well:
"SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + tablelist[t].Trim() + "'";
What is the same way in java?
Thanks for help.

sql="SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + Table_list[t] + "'";
should be changed to:
sql="SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + table_list.get(t).trim() + "'";

In Java, brackets access is only allowed for plain arrays. You declare an array using brackets String[] stringArray. Internally, Java handles a char array inside the String.
Looking at your code, looks like you're confusing a String and a List<String (or ArrayList<String>).
In order to access to a List/ArrayList element, you should use get method (note that I'm using table_list, not Table_list):
//wrong
sql="SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + table_list[t] + "'";
//right
sql="SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + table_list.get(t).trim() + "'";
Note that by doing this, your code is weak to an SQL Injection attack. Instead, you should use PreparedStatement to handle this:
sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ?";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, table_list.get(t));
ResultSet rs = stmt.executeQuery();
Also, please change the name of your variables, since table_list and Table_list can be easily confused by code readers (it would result confusing even to you).

Related

How to use ilike and % in createSQLQuery in hibernate java

I have made a sql query now i need to add search from it. it needs to search from userfullname the given keyword query is working in postgresql but it is not working with CreateSqlQuery.
sqlQuery = "select * from ( " + sqlQuery + ") a where a.payeeName ilike :searchpayeename ";
SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(sqlQuery)
.addScalar("id", new LongType());
query.setParameter("searchpayeename", "%"+payee + "%");
It is not giving me result while if i run same query in sql it is giving result. Any Idea.
Operator iLike not work with jpql, only with native query.
If you want use jpql you need simulate the iLike function using toLowerCase() on both sides of query.
jpqlQuery = "SELECT a FROM EntityName a WHERE LOWER(a.payeeName) LIKE :searchpayeename";
SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(jpqlQuery)
.addScalar("id", new LongType());
query.setParameter("searchpayeename", "%" + payee.toLowerCase() + "%");
Or using createNativeQuery:
sqlQuery = "SELECT * FROM EntityName a WHERE " +
"LOWER(a.payeeName) LIKE LOWER(CONCAT('%',:searchpayeename, '%'))";
SQLQuery query = sessionFactory.getCurrentSession().createNativeQuery(sqlQuery)
.addScalar("id", new LongType());
query.setParameter("searchpayeename", "%" + payee.toLowerCase() + "%");

java sql statement version error

this is what i got
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: 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 'order by idconsumo' at line 1
java.lang.IllegalArgumentException: Cannot set a null TableModel
code
sSQL = "select c.idconsumo,c.idreserva,c.idproducto,p.nombre,c.cantidad,c.precio_venta "
+ ",c.estado from consumo c inner join producto p on c.idproducto=p.idproducto"
+ " where c.idreserva = " + buscar +" order by idconsumo";
but still save it in the database. If i exit the app and open it again then the
record is added
First of all as Jon suggested, use the parametrized SQL.
You need to make few changes to the SQL as below:
"select c.idconsumo, c.idreserva, c.idproducto, p.nombre, c.cantidad, c.precio_venta, c.estado from consumo c inner join producto p on c.idproducto=p.idproducto where c.idreserva = " + buscar +" order by c.idconsumo";
Make sure if buscar is a variable and c.idreserva is non-int column then add single quotes around it like c.idreserva = '" + buscar +"' and order by c.idconsumo
Using prepared statement:
String sql = "select c.idconsumo, c.idreserva, c.idproducto, p.nombre, c.cantidad, c.precio_venta, c.estado from consumo c inner join producto p on c.idproducto=p.idproducto where c.idreserva = ? order by c.idconsumo";
PreparedStatement prepStmt = conn.prepareStatement(sql);
//if buscar is string type
prepStmt.setString(1, buscar);
ResultSet rs = prepStmt.executeQuery();
Query syntax error. Please check:
String sql = " select c.idconsumo,c.idreserva,c.idproducto,p.nombre,"
+" c.cantidad,c.precio_venta, c.estado "
+" from consumo c inner join producto p on "
+" c.idproducto=p.idproducto "
+" where c.idreserva ='" + buscar +"' order by c.idconsumo ";
PreparedStatement would be more accurate to use.
A PreparedStatement is a special kind of Statement object with some useful features. Remember, you need a Statement in order to execute either a query or an update. You can use a PreparedStatement instead of a Statement and benefit from the features of the PreparedStatement.
The PreparedStatement's primary features are:
Easy to insert parameters into the SQL statement. Easy to reuse the
PreparedStatement with new parameters. May increase performance of
executed statements. Enables easier batch updates.
String sql = " select c.idconsumo,c.idreserva,c.idproducto,p.nombre,"
+" c.cantidad,c.precio_venta, c.estado "
+" from consumo c inner join producto p on "
+" c.idproducto=p.idproducto "
+" where c.idreserva = ? order by c.idconsumo ";
PreparedStatement preStmt = conn.prepareStatement(sql);
preStmt.setInt(1, buscar);
ResultSet rs = preStmt.executeQuery();

Launching two query via java code

I want to execute two queries in my PostgreSQL database via code java.
The first one create a temporary view and the second one get some data from this view.
This is my code:
String sql = "create or replace temp view recap as "
+ "select id_salarie, concat(nom, ' ', prenom) as np, hour_salary, id_chantier, id_activity, SUM(nb_heures) as s_hn, SUM(nb_heures_s) as s_hs, value_update, (hour_salary*SUM(nb_heures)) as cost_hn, ((hour_salary*value_update)*SUM(nb_heures_s)) as cost_hs "
+ "from pointage_full pf, salarie s, hs_increase hsi "
+ "where s.id = pf.id_salarie "
+ "and hsi.etat = 1 "
+ "and id_chantier = "+this.idProject+" and id_salarie <> id_chef "
+ "group by id_salarie, np, hour_salary, id_activity, id_chantier, value_update "
+ "order by id_salarie DESC;"
+ ""//=================execute the second query to get costs from created view===========================
+ "select id_activity, sum(cost_hn) as sm_cost_hn, sum(cost_hs) as sm_cost_hs, (sum(cost_hn)+sum(cost_hs)) as cost_activity "
+ "from recap "
+ "group by id_activity "
+ "order by id_activity asc;";
ResultSet res = state.executeQuery(sql);
while (res.next()) {
//---doing my stuff...
}
But I get this error:
org.postgresql.util.PSQLException: No results returned by the query.
You cannot execute more than one statement with a single executeXXX() call - especially not a DDL statement and a query.
But you don't need to create that (temporary) view in the first place. Also the order by inside the view is also useless as you are re-ordering the rows in the final statement again.
You can do what you want with one single statement:
select id_activity, sum(cost_hn) as sm_cost_hn, sum(cost_hs) as sm_cost_hs, (sum(cost_hn)+sum(cost_hs)) as cost_activity
from (
select id_salarie,
concat(nom, ' ', prenom) as np,
hour_salary,
id_chantier,
id_activity,
SUM(nb_heures) as s_hn,
SUM(nb_heures_s) as s_hs,
value_update,
(hour_salary*SUM(nb_heures)) as cost_hn,
((hour_salary*value_update)*SUM(nb_heures_s)) as cost_hs
from pointage_full pf, salarie s, hs_increase hsi
where s.id = pf.id_salarie
and hsi.etat = 1
and id_chantier = ?
and id_salarie <> id_chef
group by id_salarie, np, hour_salary, id_activity, id_chantier, value_update
) as recap
group by id_activity
order by id_activity asc;
You should also use a PreparedStatement instead of concatenating parameters into your SQL. If you have the above query in a String, you can do something like this:
PreparedStatement pstmt = connection.prepareStatement(QUERY);
pstmt.setInt(1, this.idProject);
ResultSet rs = pstmt.executeQuery();
while (rs.next()
{
// process result set
}
I'm pretty sure this will be faster than first creating a temp view and then querying that.

SQL INSERT INTO does not work properly (in Java)

I have sql code in java class. The code is just like this below.
private void SummTEkspor(){
try {
bln = (String) cmbBln.getSelectedItem();
thn = (String) cmbThn.getSelectedItem();
String sql1 ="DELETE FROM a.dbo.t_export";
String sql2 ="INSERT INTO a.dbo.t_export\n" +
"SELECT * FROM b.dbo.export b WHERE b.sk_batch IN \n" +
"(SELECT sk_batch from batch_hdr WHERE bln_proses="+bln+
"AND thn_proses="+thn;
Statement st = kon.conn.createStatement();
int rs = st.executeUpdate(sql1);
int rsl = st.executeUpdate(sql2);
} catch (Exception x) {
System.out.println("FAILED");;
}
}
when i run the sql1, it works, but when sql2, it did not work properly, and just display FAILED . I guess the query in sql2 didn't take any value from what selected combo box. How can i solve that? Thanks for any reply
The problem is because you query is not proper :
INSERT INTO a.dbo.t_export\n" +
"SELECT * FROM b.dbo.export b WHERE b.sk_batch IN \n" +
"(SELECT sk_batch from batch_hdr WHERE bln_proses="+bln+
"AND thn_proses="+thn;
When you are creating a second select sub-query, you have not closed the ) bracket.
Try this :
INSERT INTO a.dbo.t_export" +
"SELECT * FROM b.dbo.export b WHERE b.sk_batch IN " +
"(SELECT sk_batch from batch_hdr WHERE bln_proses='"+bln+
"' AND thn_proses='"+thn + "')";
You open a bracket in (SELECT sk_batch f and never close it.
Use System.out.println(sql2); in order to see how the second query looks like, it could also be that one of the parameters thn and bln are null for example.
Fix the Query, quote the string values and put proper spaces.
String bln="testing";
String thn="abc";
String sql2 ="INSERT INTO a.dbo.t_export\n" +
"SELECT * FROM b.dbo.export b WHERE b.sk_batch IN \n" +
"(SELECT sk_batch from batch_hdr WHERE bln_proses='"+bln+
"' AND thn_proses='"+thn+"')";
Maybe there are som ereasons:
- closing braket in second select statement
- if bln_proses or thn_proses are strings then you have to use ' character to encompass the values
First of all you have put \n in your queries which is unnecessary, then Qualifying the table a.dbo.t_export is not needed.
Instead of:
String sql2 ="INSERT INTO a.dbo.t_export\n" +
"SELECT * FROM b.dbo.export b WHERE b.sk_batch IN \n" +
"(SELECT sk_batch from batch_hdr WHERE bln_proses="+bln+
"AND thn_proses="+thn;
Try:
String sql2 ="INSERT INTO dbo.t_export " +
"SELECT * FROM b.dbo.export b WHERE b.sk_batch IN " +
"(SELECT sk_batch from batch_hdr WHERE bln_proses="+bln+
" AND thn_proses="+thn +")";
If your columns are of Varchar type then you have to put values inside '' (Single Quotes).
Above query will work. But I suggest you to not use this approach because there is a chance of SQL Injection. Use Precompiled statements to avoid SQL Injection.
Try this query
String sql2 ="INSERT INTO a.dbo.t_export" +
"SELECT * FROM b.dbo.export b WHERE b.sk_batch IN " +
"(SELECT sk_batch from batch_hdr WHERE bln_proses="+bln+
"AND thn_proses="+thn+ ")";
bln_proses & thn_proses these are from same table batch_hdr ???

SQLException: Column AD not in specified tables - column AD never specified

I try to create a PreparedStatement:
stmt = conn.prepareStatement("SELECT POLBRP, POLTYP, POLNOP, INCPTP, TRMTHP, " +
"CLTKYP , CANDTP, POLSTP, EXPRYP, OINCPP, CANRNP, PAYMDP,
KCNFLP, KCRTSP, KACADP, KSCHMP, EXPRYP FROM "
+ POLHDR + " WHERE POLNOP = " + idNumber +
" AND POLBRP = " + branch + " AND POLTYP = " + product +
" AND OINCPP <= "+date );
And this throws an SQLException: [SQL0206] Column AD not in specified tables.
I have no idea where it's getting column AD from as I never specified it in the select clause (unless I'm being completely blind and stupid)
Can anyone help?
If your variables are strings, e.g. branch
" AND POLBRP = " + branch + " ...
then you forgot to quote the values
" AND POLBRP = '" + branch + "' ...
but the real solution is using placeholders
... AND POLBRP = ? ...
which would prevent such problems once and for all, this is what PreparedStatement is designed for
Try to change your query into this:
SELECT
POLBRP,
POLTYP,
POLNOP,
INCPTP,
TRMTHP,
CLTKYP,
CANDTP,
POLSTP,
EXPRYP,
OINCPP,
CANRNP,
PAYMDP,
KCNFLP,
KCRTSP,
KACADP,
KSCHMP,
EXPRYP
FROM TableName WHERE POLNOP = ? AND POLBRP = ? AND POLTYP = ? AND OINCPP <= ?";
Then use:
stmt.setString(1, "ValueOfPOLNOP");
...
When your query is being executed ? will be replaced with the value you passed into PreparedStatement#setString(int, String) method
Preventing SQL Injection in Java shows the proper use of PreparedStatement:
Prepared Statements Variables passed as arguments to prepared
statements will automatically be escaped by the JDBC driver.
Example: ps.1
String selectStatement = "SELECT * FROM User WHERE userId = ? ";
PreparedStatement prepStmt = con.prepareStatement(selectStatement);
prepStmt.setString(1, userId);
ResultSet rs = prepStmt.executeQuery();
From the same source, following in the same section:
Although Prepared Statements helps in defending against SQL Injection,
there are possibilities of SQL Injection attacks through inappropriate
usage of Prepared Statements. The example below explains such a
scenario where the input variables are passed directly into the
Prepared Statement and thereby paving way for SQL Injection attacks.
Example: ps.2
String strUserName = request.getParameter("Txt_UserName");
PreparedStatement prepStmt = con.prepareStatement("SELECT * FROM user WHERE userId = '+strUserName+'");

Categories