Search code examples
javaminecraftbukkit

How I properly prepare JDBC PreparedStatment?


I started to work at my own Minecraft plugin. I need database connection to do so. I try to execute query and I get errors that I can't find solutions for.

Here is the code of function that I'm using:

public void checkIfUserExists(String login, Connection connection) {
    String query = "SELECT login FROM edvault.users WHERE login = ?";
    try {
        PreparedStatement statement = connection.prepareStatement(query);
        statement.setString(1, login);
        ResultSet rs = statement.executeQuery();
        if (!rs.next()){
            String query2 = "INSERT INTO edvault.users (login) VALUES ?";
            PreparedStatement statement2 = connection.prepareStatement(query2);
            statement2.setString(1 , login);
            int result = statement2.executeUpdate();
            if (result != 1){
                Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "<DBINFO> ERROR OCCURRED WHILE INSERTING NEW USER" +
                        " TO DATABASE");
            } else {
                Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN + "<DBINFO> ADDED NEW USER TO DATABASE : LOGIN - "+
                        login);
            }
        } else
            Bukkit.getConsoleSender().sendMessage("<DBINFO> USER ALREADY EXISTS IN DATABASE");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

And here is the exception that console returns to me (this is exception for the first query, where login is xEdziu):

[22:26:21] [Server thread/WARN]: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'xEdziu' in 'where clause'

Solution

  • Replace

    INSERT INTO edvault.users (login) VALUES ?
    

    with

    INSERT INTO edvault.users (login) VALUES (?)