问题描述:

Is it more efficient to query a MySQL database in Java whilst specifying the fields in the query or more efficient to use the * wildcard?

My current code is

try (Statement statement = SQL.connection.createStatement()) {

try (ResultSet rs = statement.executeQuery("SELECT player_name, ip FROM " + SQL.database + "." + TableType.PlayerProfile.tableName + " WHERE ip='" + getPlayerIP(args[0]) + "' AND not(player_name='" + args[0] + "');")) {

if (!rs.isBeforeFirst()) {

sender.sendMessage("§7No accounts are associated with this player's ip");

} else {

sender.sendMessage("§7" + getServer().getOfflinePlayer(args[0]).getName() + "'s §lpossible §7alternative accounts:");

while (rs.next()) if (!args[0].equalsIgnoreCase(rs.getString("player_name"))) sender.sendMessage("§7" + getServer().getOfflinePlayer(rs.getString("player_name")).getName());

}

}

} catch (Exception exception) {

exception.printStackTrace();

}

So the query is

"SELECT player_name, ip FROM " + SQL.database + "." + TableType.PlayerProfile.tableName + " WHERE ip='" + getPlayerIP(args[0]) + "' AND not(player_name='" + args[0] + "');"

and then im using the Java code rs.getString("player_name") to get one of fields I need (I do the same for the ip field later)

Is this efficient or should I use the * wildcard instead of specifieng the fields I will be using with the Java code?

网友答案:

Of course it's more efficient to specify/reduce the fields you are trying to access. Less data to access by the RDBMS. Less Data to transfer via network in case you're trying to access a remote DB. Furthermore The * specifier does not guarantee the order of the returned fields. If your code is supposed to work with different DB Engines you may be surprised to see that the returned column #3 refers to a different content (been there done that). So even if you're trying to access the full width of a statement/table it is still saver to explicitly specify the cols you like to access.

相关阅读:
Top