How to display values from sql statement - java

I am using netbeans.
I have a table 'incident' with column 'priority' which can hold values priority 1 , priority 2.
I have created a jcombobox with 3 options - select all( to select all the rows) / priority 1(to select rows with priority 1 and so on) / priority 2. Options are passed through prioritybox.getSelected().
I want to know any possible sql statement so that if i select the option 'select all' , all the entries of the table should be selected.
If i choose priority 1
then the statement
select * from incident where priority='"+prioritybox.getSelected()+"';
gets executed correctly i.e. it select the rows which having priority=priority1. But if i select the option 'select all ' then this statement becomes invalid as no such row is there with priority value = select all.I don't want to use if-else . Any other possible solution??

You need to use if clause.
Go with the following code
String strSelect1 = "select * from table";
if(prioritybox.getSelectedItem()!="your option")
{ strSelect1=strSelect1+" where Priority='"+prioritybox.getSelectedItem()+"'"; };
Now keep on adding this if statements for rest of the fields.

For purely SQL you could do:
select * from incident where priority='"+prioritybox.getSelected()+"' OR '"+prioritybox.getSelected()+"' = 'select all';
However it's probably easier to add logic to add the where clause if the option is not select all.

You can pass special character '%' to query which will return all characters for that you need to replace = with like query and you need to set '%' as your 'SelectAll' value, your query can be like this
select * from incident where priority like '"+prioritybox.getSelected()+"';

String query="";
if(!prioritybox.getSelected().toString().equals("select all")){
query="select * from incident where priority='"+prioritybox.getSelected()+"'";
}
else {
query="select * from incident" ;
}

Related

JPA Union Equivelant Need for Adding Constant to Query Result

I need union equivelant for Union. I know we can do this by joining selections but i couldn't do that for adding constant to query results. Here is my sql
SELECT MIN(t1.EXAMPLE_NUMBER)
FROM
(
SELECT 1 AS EXAMPLE_NUMBER
UNION ALL
SELECT EXAMPLE_NUMBER + 1
FROM selection.SELECTION
) t1
LEFT OUTER JOIN selection.SELECTION t2
ON t1.EXAMPLE_NUMBER = t2.EXAMPLE_NUMBER
WHERE t2.EXAMPLE_NUMBER IS NULL;
This query need for finding minimum unused integer for the column. Lets say:
EXAMPLE_NUMBER
1
4
5
I need to get 2 as a result for this case. That is the sql for this. So here is my question:
I use QueryDsl-JPA for this. Since JPA 2, i can't use UNION. So i can't do this sql with querydsl-jpa, i was thinking about go like this:
JPAQuery baseQuery = new JPAQuery(em);
SubQueryExpression handleNumberOne = baseQuery.select(Expressions.constant(1));
SubQueryExpression selectAvailableMinNumber = baseQuery.select(selection.exampleNumber.add(1)).from(selection);
baseQuery.union(handleNumberOne, selectAvailableMinNumber); // NO UNION AVAILABLE
Is it any available way to do this with querydsl-JPA? I don't want to include querydsl-sql library just for this reason, I'm looking for JPA style solution. What i tried so for to try adding constant (1 in my case) to result of select query without union. By this way I may able to continue. Any suggestion?
You do not have to generate all the numbers to get this information.
For all numbers except 1, you can do:
select s.example_number + 1
from selection s
where not exists (select 1
from selection s2
where s2.example_number = s.example_number + 1
)
fetch first 1 row only; -- or limit 1
If you also want to get "1" if it doesn't exist, then:
select (case when min_en > 1 then 1
else s.example_number + 1
end)
from selection s cross join
(select min(example_number) as min_en from selection) mins
where not exists (select 1
from selection s2
where s2.example_number = s.example_number + 1
)
fetch first 1 row only; -- or limit 1

Spring namedParameterJdbcTemplate and a list parameter: how to check if it is null in SQL?

I'm using spring's NamedParameterJdbcTemplate because I have a SELECT ... IN () in my SQL query, as explained here.
In our specific case, the business logic should be:
- If the list of id's to check is null or empty, omit the entire IN condition
- If the list contains id's, use the IN condition like normal
So we programmed it like this:
SELECT * FROM table WHERE (:ids IS NULL or table.column IN (:ids))
This query works if the :ids is indeed a NULL or empty list, but it fails if it is not because the way spring fills in the parameters for a list of 3 values is like this:
SELECT * FROM table WHERE ((?,?,?) IS NULL or table.column IN (?,?,?))
and you cannot do "IS NULL" on the triple question mark statement. Is there any easy way to do solve this directly in the SQL query, thus not using Java code (we don't want to do string maniuptlation in the sql query in Java)?
You could try reversing the order like this:
SELECT * FROM table WHERE (table.column IN (:ids) or :ids IS NULL)
Since your 3 id case will satisfy the first condition, the 'or' may not be evaluated. This might depend on your DB though. This works with Hibernate + Oracle, but I don't see it working with Sybase IQ + NamedParameterJdbcTemplate so your mileage may vary.
If your DB supports Common Table Expressions (CTE's), you can try this:
with
x as (
select column
from table
where column in (:ids)
)
select *
from table
where (table.column in (:ids) or (select count(*) from x) = 0)

How to order by a specific column a MySQL query with Java and Hibernate?

I'm trying to use the same query to sort my table columns but when I pass as a parameter the column to ORDER BY, it adds quotes before and after my column name. If you are using ORDER BY parameter, the column name have to be written without being between quotes or MySQL is going to ignore it.
Example or query to execute:
select * from app_user ORDER BY mobile_token ASC LIMIT 0 , 20
This is what hibernate send to MySQL:
select * from app_user ORDER BY 'mobile_token' ASC LIMIT 0 , 20
Java query:
query = JPA.em().createNativeQuery("select * from app_user ORDER BY :column ASC LIMIT :init , :page",AppUser.class);
query.setParameter("column", column);
query.setParameter("init", pageNumber*pageSize);
query.setParameter("page", pageSize);
I could change the NativeQuery by:
"select * from app_user ORDER BY "+column+" ASC LIMIT :init , :page"
but this is going to become my app unsafety.
You can only pass values as parameters to a query. Not column or field names. That would make it impossible for the database to know which columns are actually used in the query, and thus make it impossible to prepare the execution plan.
So your solution using concatenation is the only one. Just make sure the column doesn't come from the user. Or if it comes from the user, that it's a valid column name and that the user is allowed to use it.

Select query with multiple where clauses

I have a list of serial numbers: 111111, 222222, AAAAAA, FFFFFF and I want to return a corresponding value or null from a table depending on whether or not the value exists.
Currently I loop through my list of serial numbers, query using the following statement:
"SELECT cnum FROM table WHERE serial_num = " + serialNumber[i];
and then use the value if one is returned.
I would prefer to do this is one query and get results similar to:
Row | cnum
------------
1 | 157
2 | 4F2
3 | null
4 | 93O
5 | null
6 | 9F3
Is there a query to do this or am I stuck with a loop?
It sounds as if you have some sort of Java Array or Collection of serial numbers, and perhaps you want to check to see if these numbers are found in the DB2 table, and you'd like to do the whole list all at once, rather than one at a time. Good thinking.
So you want to have a set of rows with which you can do a left join to the table, with null indicating that the corresponding serial was not in the table. Several answers have started to use this approach. But they are not returning your row number, and they are using SELECT UNION's which seems a round-about way to get what you want.
VALUES clause
Your FROM clause can be a "nested-table-expression"
which can be a (fullselect)
with a correlation-clause. The (fullselect) can, in turn, be a VALUES clause. So you could have something like this:
FROM (VALUES (1, '157'), (2, '4F2'), (3, '5MISSING'), (4, '93O'), ...
) as Lst (rw, sn)
You can then LEFT JOIN this to the table, and get a two-column result table like you asked for:
SELECT Lst.rn, t.serial_num
FROM (VALUES (1, '157'), (2, '4F2'), (3, '5MISSING'), (4, '93O'), ...
) as Lst (rw, sn)
LEFT JOIN sometable t ON t.serial_num = Lst.sn
With this method, you will probably need a loop to build your dynamic SQL statement string, using the values from your collection.
If it was embedded SQL, we might be able to reference a host array variable containing your serial numbers. But alas, in Java I am not sure how to manage using the list directly in SQL, without using some loop.
If you use only an "in" it is not going to return null for the missing value forcing you to do some coding in the application (probably the most efficient way).
If you wanted the database to do all the work (may or may not be ideal) then
you would have to trick db2 into returning your list regardless.
Something like this might work, faking the null values to be returned from sysdummy with the common table expression (with part):
with all_serials as (
select '111111' as serialNumber from sysibm.sysdummy1 union all ,
select '222222' as serialNumber from sysibm.sysdummy1 union all ,
select 'AAAAAA' as serialNumber from sysibm.sysdummy1 union all ,
select 'FFFFFF' as serialNumber from sysibm.sysdummy1
)
select
t1.serialNumber,
t2.serialNumber as serialNumberExists
from
all_serials as t1 left outer join
/* Make sure the grain of the_Table is at "serialNumber" */
the_table as t2 on t1.serialNumber = t2.serialNumber
You can use the SQL IN keyword. You'd need to dynamically generate the list, but basically it'd look like:
SELECT cnum FROM table WHERE serial_num in ('111111', '2222222', '3333333', 'AAAAAAA'...)
Try something like:
select t.cnum
from
(select '111111' serial_num from sysibm.sysdummy1 union all
select '222222' serial_num from sysibm.sysdummy1 union all
select 'AAAAAA' serial_num from sysibm.sysdummy1 union all
select 'FFFFFF' serial_num from sysibm.sysdummy1) v
left join table t on v.serial_num = t.serial_num
I'm not sure if I get you correctly, but this could help:
String query = "SELECT cnum FROM table WHERE ";
for(int i = 0; i < serialNumber.length; i++)
query += "serial_num='" + serialNumber[i] + "' OR ";
query += "serial_num IS NULL "
System.out.println(query);

Java PreparedStatement can't identify placeholders in subquery

When using a Java PreparedStatement, the question-mark placeholders aren't being detected. It would throw an error "The column index is out of range: 1, number of columns: 0" when invoking statementName.setLong(1, 123). My example is from Postgres 8.4, but the problem occurs before the SQL has a chance to make it to the SQL server.
After comparing against some working prepared statements, I realized that the broken one contained a subquery similar to:
SELECT * FROM (
SELECT DISTINCT (name)
id,
name
FROM MyTable
WHERE id > ?
ORDER BY name) AS Level1
ORDER BY 1
The solution that worked for me was to convert the query to a CTE (Common Table Expression). The revised query looks like this:
WITH Level1 AS (
SELECT DISTINCT (name)
id,
name
FROM MyTable
WHERE id > ?
ORDER BY name)
SELECT *
FROM Level1
ORDER BY 1
In JDBC, the parameter indexes for prepared statements begin at 1 instead of 0.

Categories