在 PreparedStatement 中获取 NullPointerException

问题描述

所以我应该使用 MysqL 连接到 JDBC。 我有一个连接功能,它告诉我它工作正常。但是我在 PreparedStatement 代码中遇到了问题。

我的实际代码没有显示任何错误,但是当我运行时,我的终端显示数据库连接成功”,然后给我“线程“main”中的异常java.lang.NullPointerException”。

这将我引导到我的行 -- PreparedStatement Posted = conn.prepareStatement("INSERT INTO people(firstName,lastName) VALUES ('"+var1+"','"+var2+"')")

所以在运行我的 post() 时会断开连接;这对我来说没有任何意义......我应该检查什么来解决这个问题?

    public static void main(String[] args) throws Exception{
        People project = new People();
        project.createConnection();
        project.post();
    }
    
    void createConnection(){
        try {
            String driver = "com.MysqL.cj.jdbc.Driver";
            Class.forName(driver);
            java.sql.Connection conn = DriverManager.getConnection("jdbc:MysqL://localhost:3306/peopledb","root","root");
            if(conn != null){System.out.println("Database connection success");}
            
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(People.class.getName()).log(Level.SEVERE,null,ex);
        } catch (sqlException ex) {
            Logger.getLogger(People.class.getName()).log(Level.SEVERE,ex);
        }
        
    }
    
    void post() {
        try {
            final String var1 = "John";
            final String var2 = "Doe";
            PreparedStatement posted = conn.prepareStatement("INSERT INTO people(firstName,'"+var2+"')");
            posted.executeUpdate();
            if(conn != null){
                System.out.println("Insert Completed");
            }
        } catch (sqlException ex) {
            Logger.getLogger(People.class.getName()).log(Level.SEVERE,ex);
        }
    }

}

解决方法

您可以尝试以下修改来解决此特定问题。

    public static void main(String[] args) throws Exception{
        People project = new People();
        project.createConnection();
        project.post();
    }
    private java.sql.Connection conn; //create attribute accessible by both methods
    void createConnection(){
        try {
            String driver = "com.mysql.cj.jdbc.Driver";
            Class.forName(driver);
            //assign value to attribute instead of local variable
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/peopledb","root","root");
            if(conn != null){System.out.println("Database connection success");}
            
         } catch (ClassNotFoundException ex) {
            Logger.getLogger(People.class.getName()).log(Level.SEVERE,null,ex);
        } catch (SQLException ex) {
            Logger.getLogger(People.class.getName()).log(Level.SEVERE,ex);
        }
        
    }
    
    void post() {
        try {
            final String var1 = "John";
            final String var2 = "Doe";
            //Below is prone to SQL Injection. 
            //PreparedStatement posted = conn.prepareStatement("INSERT INTO people(firstName,lastName) VALUES ('"+var1+"','"+var2+"')");
            //Recommended approach
            PreparedStatement posted = conn.prepareStatement("INSERT INTO people(firstName,lastName) VALUES (?,?)");
            posted.setString(1,var1); 
            posted.setString(2,var2);
            //we expect 1 row to inserted from this statement and executeUpdate
            //will return the number of affected rows
            if(posted.executeUpdate() ==1){
                System.out.println("Insert Completed");
            }
        } catch (SQLException ex) {
            Logger.getLogger(People.class.getName()).log(Level.SEVERE,ex);
        }
    }

}