java - 连接到数据库的方法给出空指针异常

标签 java mysql servlets

目前我有一个名为work的java对象,该对象内部有这个方法。

public void Connection(Connection conn) throws NamingException, SQLException {


    // Setup the Database datasource
    Context ctx = new InitialContext();
    Context env = (Context) ctx.lookup("java:comp/env");
    DataSource ds = (DataSource) env.lookup("jdbc/carRentalSystem");
    conn = ds.getConnection();
}

我在 servlet 内部调用此方法来连接到我的数据库并添加一个表行。出于某种原因,我在通过调试运行它时不断收到空指针异常。谁能指导我如何让它正常工作?

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    // Obtain submitted form data

    Work work = new Work();
    String firstName = req.getParameter("First_Name");
    String lastName = req.getParameter("Last_Name");
    String username = req.getParameter("User_Name");
    String email = req.getParameter("Email_Address");
    String password = req.getParameter("Password");

    ResultSet rs = null;
    Connection conn = null;
    Statement st = null;

    try {
        work.Connection(conn);


        // Prepare the SQL statmenet to insert the values

        PreparedStatement stmt = conn.prepareStatement("INSERT INTO userdetails(First_Name, Last_Name, Email_Address, Password, User_Name)  VALUES (?,?,?,?,?)");
        stmt.setString(1, firstName);
        stmt.setString(2, lastName);
        stmt.setString(3, email);
        stmt.setString(4, password);
        stmt.setString(5, username);

        // Execute the insert
        stmt.executeUpdate();
        conn.close();

        // Dispatch into success page
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("login.jsp");
        requestDispatcher.forward(req, res);
    } catch (Exception e) {
        work.ErrorHome(req, res, e);
    } finally {
        try {
            if (st != null)
                st.close();
        } catch (java.sql.SQLException e) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (java.sql.SQLException e) {
        }
        try {
            if (rs != null)
                rs.close();
        } catch (java.sql.SQLException e) {
        }
    }
}

}

最佳答案

重写您的 Connection(Connection conn) 方法,如下所示:

public Connection createConnection() throws NamingException, SQLException {
    // Setup the Database datasource
    Context ctx = new InitialContext();
    Context env = (Context) ctx.lookup("java:comp/env");
    DataSource ds = (DataSource) env.lookup("jdbc/carRentalSystem");
    return ds.getConnection();
}

稍后,在源代码中使用:

conn = work.createConnection();

而不是:

work.Connection(conn);

这应该可以避免您的 NPE。

关于java - 连接到数据库的方法给出空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46709699/

相关文章:

JAVA——代表月份和年份

java - 反射(reflection)的替代方案

java - 如何使用 Spring Boot 将配置读取到 map

java - Tomcat 与 Weblogic JNDI 查找

PHP Swiftlet mysqli 错误

java - 无法在 glassfish 3.1 中将字符集从 ISO-8859-1 更改为 UTF-8

MySQL 连接性能问题与 OR 条件

mysql用单​​个sql更新多个表以获得sum(qty)

java - ServletFileUpload 异常

java - 重定向和 POST 方法