PreparedStatement保持无效

时间:2015-04-20 18:45:29

标签: java servlets jdbc

我目前正在servlet中创建一个私有方法。但我的PreparedStatement不断返回null

private ArrayList<String> emails(String id) {
        ArrayList<String> email= new ArrayList<String>();
        try {
            PreparedStatement st = null;
            ResultSet data = null;
            DriverManager.getConnection(
                    "jdbc:postgresql://localhost/test",
                    "test", "test");
            String sql = "SELECT email FROM  hdpr.email_table WHERE id='"
                    + id+ "'";
            data = st.executeQuery(sql);
            while (data.next()) {
                email.add(data.getString("email"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        } catch (NullPointerException e) {

            e.getMessage();
        }

        return email;

    }

1 个答案:

答案 0 :(得分:3)

试试这样:

private ArrayList<String> emails(String id) {
    ArrayList<String> email= new ArrayList<String>();
    try {
        PreparedStatement st = null;
        ResultSet data = null;

        // Creating a new connection
        Connection con = DriverManager.getConnection(
                "jdbc:postgresql://localhost/test",
                "test", "test");  

        // your SQL Query now with a ? as parameter placeholder
        String sql = "SELECT email FROM  hdpr.email_table WHERE id = ?";

        // creating a new preparedStatement using your sql query
        st = con.prepareStatement(sql);

        // set the first ? to the value of id
        st.setString(1, id);

        data = st.executeQuery();
        while (data.next()) {
            email.add(data.getString("email"));
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    } catch (NullPointerException e) {

        System.err.println(e.getMessage());
    }

    return email;

}

您还应该看一下步骤:

  1. 如果您将null分配给变量,则null如果您尝试从该对象调用方法,则NullpointerException将始终发生。

    < / LI>
  2. 要使用PreparedStatement st,您需要使用连接和SQL查询创建preparedStatement来初始化它。

  3. 不要使用+运算符向SQL查询添加参数 - 这将为 SQL注入打开大门,为此我们准备好了语句并{{1} },setString(),...

  4. 你应该看看教程,比如说:http://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/