简体   繁体   English

检查数据库中是否存在行,并返回布尔值

[英]Check if row exists in db, and return boolean

I have this funcion that takes a name and check in a database if a row exists with that name.我有这个函数,它接受一个名称并检查数据库中是否存在具有该名称的行。 However, i dont know how to determine if the row exists or not.但是,我不知道如何确定该行是否存在。

My code right now is我现在的代码是

public static boolean rowExists(String player) throws SQLException {
    String sql = "SELECT EXISTS(SELECT * FROM currency WHERE name='"+player+"');";
    Bukkit.broadcastMessage(player);
    Statement stmt = con.createStatement();
    
    ResultSet up = stmt.executeQuery(sql);
    boolean nut = up.next();
    Bukkit.broadcastMessage("nut: " + nut + "  ");

    return nut;
}

nut is the boolean where true is the entry exists, and false it does not. nut 是布尔值,其中 true 表示条目存在,而 false 则不存在。 Currently nut always returns as true, whether the row exists or not.目前 nut 总是返回为真,无论该行是否存在。

Simple queries are better:简单的查询更好:

SELECT 1 FROM currency WHERE name=%s LIMIT 1

This will return a single row of 1 if it exists, an 0 rows if it doesn't exist.如果存在,这将返回单行 1,如果不存在则返回 0 行。

Also use prepared statement to avoid SQL injection.还可以使用准备好的语句来避免 SQL 注入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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