简体   繁体   中英

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. Currently nut always returns as true, whether the row exists or not.

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.

Also use prepared statement to avoid SQL injection.

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