【问题标题】:PreparedStatement staying nullPreparedStatement 保持为空
【发布时间】:2015-06-27 15:43:19
【问题描述】:

我目前正在一个 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;

    }

【问题讨论】:

  • 您将其 (st) 初始化为 null 并且永远不会重新分配它。你期待什么?
  • 您好 null_logic - 您对我的回答满意还是需要其他帮助? :)

标签: java servlets jdbc


【解决方案1】:

试试这样:

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

  2. 要使用您的 PreparedStatement st,您需要通过使用您的连接和 SQL 查询创建preparedStatement 来初始化它。

  3. 不要使用 + 运算符向 SQL 查询添加参数 - 这将为 SQL 注入 打开大门,为此我们有准备好的语句和 setString()、@987654329 @, ...

  4. 你应该看看这样的教程:http://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/

【讨论】:

  • executeQuery(String sql) 方法是在 PreparedStatement 的父类 Statement 上定义的,其中在 javadocs 中它说:“此方法不能在 PreparedStatementCallableStatement 上调用”。您应该改用st.executeQuery(),它使用“准备好的”SQL。
  • @dcsohl 谢谢!从问题中处理该代码块后,忘记从executeQuery() 中删除sql
猜你喜欢
  • 2018-11-19
  • 2014-08-29
  • 2016-06-30
  • 2012-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多