如何在JDBC中使用MySQL子查询?

前端之家收集整理的这篇文章主要介绍了如何在JDBC中使用MySQL子查询?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

示例查询

SELECT country 
FROM data 
WHERE city LIKE 
(SELECT LEFT ('jakartada',7));

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();

为什么这不能正常工作?

最佳答案
预准备语句中没有参数,但代码尝试设置参数.尝试在语句中添加参数.

String sql = " SELECT country FROM data WHERE city LIKE (SELECT LEFT (?,city    );
ResultSet rs = ps.executeQuery();

或者尝试删除设置参数的语句:

String sql = " SELECT country FROM data WHERE city LIKE (SELECT LEFT ('jakartada',7)) ";
PreparedStatement ps = koneksi.prepareStatement(sql);
ResultSet rs = ps.executeQuery();

猜你在找的MySQL相关文章