简体   繁体   中英

How to use MySQL subquery in JDBC?

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 */

在运行时设置值时,不要在准备好的语句中引用...否则它将仅作为输入而不是ps位置...从问号中删除单引号...

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),'%')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM