How to use MySQL subquery in JDBC? - java

Example query:
SELECT country
FROM data
WHERE city LIKE
(SELECT LEFT ('jakartada',7));
Example in JDBC:
String sql = " SELECT country FROM data WHERE city LIKE (SELECT LEFT ('?',7)) ";
PreparedStatement ps = koneksi.prepareStatement(sql);
ps.setString(1, city );
ResultSet rs = ps.executeQuery();
Why this doesn't work properly?

There is no parameter within the prepared statement, however the code attempts to set a parameter. Try adding a parameter to the statement.
String sql = " SELECT country FROM data WHERE city LIKE (SELECT LEFT (?,7)) ";
PreparedStatement ps = koneksi.prepareStatement(sql);
ps.setString(1, city );
ResultSet rs = ps.executeQuery();
Or try removing the statement setting the parameter:
String sql = " SELECT country FROM data WHERE city LIKE (SELECT LEFT ('jakartada',7)) ";
PreparedStatement ps = koneksi.prepareStatement(sql);
ResultSet rs = ps.executeQuery();

I believe you're making this harder than it needs to be, and at the same time you're missing something. Is this what you're trying to do?
SELECT country FROM data WHERE city LIKE 'jakarta%'
That is, are you looking for the country column from every row where the city name starts with 'jakarta'? If so, don't forget the % sign. If you don't include the % sign, then
SELECT country FROM data WHERE city LIKE 'jakarta'
and
SELECT country FROM data WHERE city = 'jakarta'
mean exactly the same thing as each other, and the LIKE operator is pointless; you may as well use the = operator.
So, it seems to me the MySQL query you want is
SELECT country FROM data WHERE city LIKE CONCAT(LEFT('jakartada',7),'%')
to add the % sign. You don't need the subselect in this case.
Like you pointed out, the Java code you need then is:
String sql = "SELECT country FROM data " .
"WHERE city LIKE CONCAT(LEFT(?,7),'%')";
PreparedStatement ps = koneksi.prepareStatement(sql);
ps.setString(1, city );
ResultSet rs = ps.executeQuery();
... process the rs records ...
rs.close(); /* please don't forget to close your result sets */

use this link for your solution and this query
http://sqlfiddle.com/#!2/c79ab/10
SELECT country FROM data
WHERE city LIKE CONCAT(LEFT('jakartada',7),'%')

Don't you quotes in your prepared statement when setting values at runtime... Otherwise it will take it as input only not for ps position... Remove single quotes from your question mark...

Related

Why I cannot put where in SQL?

I'm trying to insert a sublevel to a table from form like in the picture but why can't I use where?
String sql = "insert into BE_Tracker(sub_item) values(?) where id="+id+" ";
PreparedStatement st = con.prepareStatement(sql);
st.setString(2,addsubItem);
you cannot use where in insert into query in this way.
You can use it like, something like that
insert into MyTable1 select id,name from MyTable2 where id >5
It sounds like you really wanted an UPDATE here:
String sql = "UPDATE BE_Tracker SET sub_item = ? WHERE id = ?";
PreparedStatement st = con.prepareStatement(sql);
st.setString(1, addsubItem);
st.setString(2, id);
st.executeUpdate();
INSERT (...) VALUES (...) query cannot use with finding option WHERE ... = ....
Insert row on table BE_Tracker.
Find rows in table BE_Tracker with 'WHERE' option with 'SELECT', 'UPDATE' or 'DELETE'.

select subquery in insert query for PreparedStatement

I want to use a SELECT subquery into a INSERT query as PreparedStatement...
I am trying to fill 2 columns with custom value and the 3rd one with subquery...
query = "insert into invoiceOrders (productCode,quantity,amount) values (?,?,select price from priceTable where proCode=pCode)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(0,"productCode");
stmt.setString(1,"qty");
/*3rd column will be filled be subquery*/
n = stmt.executeUpdate();
The subquery:
select price from priceTable where proCode=pCode
must be enclosed in parentheses and make sure that it returns only 1 row.
Also what is the parameter pCode?
I think that you should replace it with ? and pass later its value with setString().
Also the setString() method's 1st argument is 1 based.
So change to this:
query = "insert into invoiceOrders (productCode,quantity,amount) values (?,?,(select price from priceTable where proCode=?))";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1,"productCode");
stmt.setString(2,"qty");
stmt.setString(3,pCode); // or stmt.setInt(3,pCode);
n = stmt.executeUpdate();

jdbc dymanic sql query with variable containg 's

I have asked this beacause i was not able to find the answer.
what i am doing is
String selectTableSQL = "SELECT * FROM diseaseinfo WHERE diseaseName =""+diseaseName +'" AND name = '"+username+"'";
it is perfecty running unless and until diseases does not contain 's type of word like
Wilms' tumor
Addison's disease
etc....
so query like
SELECT * FROM diseaseinfo WHERE diseaseName = 'Adult Still's disease' AND name = 'add';
wont execute because of ' 's on 'Adult Still's
and also in java i cant start string with String selectTableSQL = ' '; it will always be in String selectTableSQL = " ";
any solution?
To avoid this case and any syntax error or SQL Injection you have to use PreparedStatement instead :
String selectTableSQL = "SELECT * FROM diseaseinfo WHERE col1 = ? and col2 = ?";
try (PreparedStatement ps = connection.prepareStatement(selectTableSQL)) {
ps.setString(1, value_1);
ps.setString(2, value_2);
ResultSet rs = ps.executeQuery();
while(rs.next()){
//...
}
}
The correct way to use queries in JDBC is to use PreparedStatement and bind variables.
But in your case, try replacing the single quotes ' in your values with \'.
You can use a simple diseaseName.replace("'", "\\'"); to do it.

need to retrieve a database row value via sql based on values retrieved via previous sql query in java

My code goes something like this
DataBaseUtil dbBaseUtil=new DataBaseUtil();
Connection con=dbBaseUtil.getConnection();
String query="select case_id, ticket_id from VAPP_ITEM where
(person1_alt_email='" + username +"') and ticket_type='Service Request' and ticket_status not in ('Closed','Resolved')";
ResultSet rs=dbBaseUtil.getDbResultSet(query);
List<String> tickets=new ArrayList<String>();
while(rs.next())
ticket.add(rs.getString("case_Id")+"-"+rs.getString("ticket_Id"));
MyTicketUtil.searchAndOpenTicket(webui, "", tickets.get(0));
Now, once I get the element "tickets(0)", I perform some operations on it, and after the operations are performed, I need to retrieve ticket_status for the ticket on which the operations were performed - tickets(0).
However, to query the database, I need case_id and ticket_id for tickets(0). How can it be done?
I tried creating two ResultSets and a query post operations like below:
while(rs1.next())
quer1 = "select ticket_status from VAPP_ITEM where case_id=rs.getString(1) and ticket_id = rs.getString(2)";
But this is not working - console shows below error:
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot find either column "rs" or the user-defined function or aggregate "rs.getString", or the name is ambiguous.
You have included rs.getString() into string literal.
You should use PreparedStatement for such things:
quer1 = "SELECT ticket_status FROM vapp_item WHERE case_id=? AND ticket_id = ?";
PreparedStatement pstm = conn.prepareStatement(quer1);
while (rs1.next())
{
pstm.setString(1, rs.getString(1));
pstm.setString(2, rs.getString(2));
rs2 = pstm.executeQuery();
...
}

SQL Where Clause with Values Provided

I am trying to use a SQL Select statement for a query in Java. I currently have the following:
ResultSet rs = stmt.executeQuery("SELECT *" +
" FROM " + table +
" WHERE " + selection +
" VALUES " + selectionArgs);
where "selection" is a string and "selectionArgs" is a string array.
String selection = "documentFK=?";
String[] selectionArgs = { ... };
Is it possible to use the VALUES command to replace the ? like in with the INSERT command? Either way, what would be the correct syntax?
Thanks for the help.
I believe what you're looking for is the IN statement. Your query should look like this:
SELECT *
FROM table
WHERE documentFK IN ('doc1', 'doc2', 'doc3')
AND userFK IN ('user1', 'user2', 'user3')
This is (obviously) going to make your code a bit more ugly. You'll have to ensure that the WHERE keyword is used for the first clause, but the AND keyword is used for every other clause. Also, each list will have to be comma-delimited.
no, that is not the way it's done. first you create the statement from the query, using the question marks as place holders for the real values you want to put there. then you bind these values to the statement.
//the query
String sql = "SELECT " + "*" +
" FROM " + table +
" WHERE documetFK = ?";
//create the statement
PreparedStatement stmt = connection.prepareStatement(sql);
//bind the value
stmt.setInt(1, 4); //1 is "the first question mark", 4 is some fk
//execute the query and get the result set back
ResultSet rs = stmt.executeQuery();
now, if you want this thing with selection string and some args, then you're going to have a loop in your java code. not sure what your array looks like (you're not giving me that much to go on), but if it's made up from strings, it would be something like this:
//the query
String sql = "SELECT " + "*" +
" FROM " + table +
" WHERE " + selection;
//create the statement
PreparedStatement stmt = connection.prepareStatement(sql);
//bind the values
for(int i = 0; i < selectionArgs.length; i++) {
stmt.setString(i, selectionArgs[i]); //i is "the nth question mark"
}
//execute the query and get the result set back
ResultSet rs = stmt.executeQuery();
Can you use a PreparedStatement?
First of all SELECT .. WHERE .. VALUES is incorrect SQL syntax. Lose the VALUES part.
Then you're looking for prepared statements.
In your example it's going to look something like this:
String sql = "SELECT * FROM myTable WHERE documentFK=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "myDocumentFK"); // parameters start from 1, not 0. also we're assuming the parameter type is String;
ResultSet rs = pstmt.executeQuery();
Or with multiple parameters:
String sql = "SELECT * FROM myTable WHERE documentFK=? AND indexTerm=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "myDocumentFK"); // parameters start from 1, not 0. also we're assuming the parameter type is String;
pstsm.setInt(2, 100); // assume indexTerm can be 100 and is an integer
ResultSet rs = pstmt.executeQuery();
However, all of this doesn't worth your while since you can simply do the same by concatenating the value into the statement. But be aware of the SQL injections, so don't forget to escape the parameters that you're passing into the database.
PS: I was typing this way too long. You already have the answers :-)
As a side note, you may want to take a look at this to prevent SQL injections:
https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java
Sormula can select using "IN" operator from a java.util.Collection of arbitrary size. You write no SQL. It builds the SQL SELECT query with correct number of "?" parameters. See example 4.

Categories