Java / SQL:MySQLSyntaxErrorException:未知列'用户名'在' where子句'

时间:2015-07-31 14:07:52

标签: java mysql sql

我坚持使用以下代码,但我不知道为什么会出现异常。

当我将它放入phpMyAdmin的SQL字段时,字符串运行正常。

我收到了一张我想要的表,即带有1个值的表cid,即playerID。

我还在变体中使用了此代码,我说"WHERE playerID = " +playerID并且有效....

当我通过eclipse运行它时,为什么这不起作用我真的很兴奋。

是的,我在这里搜索过,找到了很多类似的MySQLSyntaxErrorException线程,但没有一个让我找到解决方案

public int getUserIDfromDBcoolpag(String inputUsername){
    System.out.println("getUserIDfromDBcoolpag called");
    int playerID = 0;
        try {
            SQLConnection.getInstance().init(DATABASE_HOST, DATABASE_PORT, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD);
            Connection connection = SQLConnection.getInstance().getConnection();
            try
            {
                String getPlayerID = "SELECT coolpag.player.id as cid FROM coolpag.player WHERE username=" +inputUsername;
                PreparedStatement statement = connection.prepareStatement(getPlayerID);
                try
                {
                    ResultSet res = statement.executeQuery();
                    try
                    {
                        while (res.next())
                        {
                            playerID = res.getInt("cid");
                        }
//                      System.out.println("LOG: output operation finished");
                    }
                    finally
                    {
                        res.close();
                    }
                }
                finally
                {
                    statement.close();
                }
            }
            finally
            {
            }

            boolean isAlive = SQLConnection.getInstance().getConnection().isClosed();
            if(isAlive){
                System.out.println("Connection is not yet closed");
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return playerID;
    }

1 个答案:

答案 0 :(得分:1)

而不是

String getPlayerID = "SELECT coolpag.player.id as cid FROM coolpag.player WHERE username=" +inputUsername;//inputUsername must be quoted

PreparedStatement statement = connection.prepareStatement(getPlayerID);

使用

String getPlayerID = "SELECT coolpag.player.id as cid FROM coolpag.player WHERE username=?";

PreparedStatement statement = connection.prepareStatement(getPlayerID);
statement.setString(inputUsername);//to avoid sql injection

Avoid sql injection