我在软件中使用SQLite本地数据库。我想根据行的赋值者检查行是否存在。例如 :"SELECT * FROM ftp WHERE Host LIKE '"+ host +"' AND Username LIKE '"+ username +"' "
"SELECT * FROM ftp WHERE Host LIKE '"+ host +"' AND Username LIKE '"+ username +"' "
但是我想获得布尔结果,所以如果找到记录则执行某项操作,如果不执行其他操作。头可以这样做吗?
这是我很累的事情,但这始终是正确的,因为它检查查询是否运行,而不检查是否返回数据。
public void ftpTableCheck(String host, String port, String username, String password){ try{ String query = "SELECT * FROM ftp WHERE Host LIKE '"+ host +"' AND Username LIKE '"+ username +"' "; PreparedStatement pst = conn.prepareStatement(query); if (pst.execute() == true){ System.out.println("true"); } }catch(Exception e){ e.printStackTrace(); } }
知道如何解决吗?谢谢
因此,您可以使用类似select count(*) ...或select (count(*) > 0) as found ...作为基本查询的内容。
select count(*) ...
select (count(*) > 0) as found ...
当您致电时executeQuery,您将得到一个ResultSet回报,您需要确定它的内容。
executeQuery
ResultSet
在您的情况下,您只期望得到单行结果,因此您可以简单地使用ResultSet#next移动到第一行,然后从中提取列值…
ResultSet#next
public void ftpTableCheck(String host, String port, String username, String password) { try { String query = "SELECT (count(*) > 0) as found FROM ftp WHERE Host LIKE ? AND Username LIKE ?"; PreparedStatement pst = conn.prepareStatement(query); pst.setString(1, host); pst.setString(2, username); try (ResultSet rs = pst.executeQuery()) { // Only expecting a single result if (rs.next()) { boolean found = rs.getBoolean(1); // "found" column if (found) { // You have rows } else { // You have no rows } } } } catch (SQLException e) { e.printStackTrace(); } }
就拿仔细看看JDBC数据库访问和使用预处理语句了解更多详情