在输入数据到mysql时获取连接null错误

时间:2016-06-21 12:00:15

标签: java mysql

这是连接类

public class ConnectionManager {

    Connection cn = null;

    public Connection getConnection() throws ClassNotFoundException, SQLException {
        String dbPath = "jdbc:mysql://localhost:3306/postjob";
        String username = "root";
        String password = "root";
        Class.forName("com.mysql.jdbc.Driver");

        cn = DriverManager.getConnection(dbPath, username, password);
        return cn;
    }

    public void closeConnection() throws SQLException{
        cn.close();


    }
}

这是我的服务类

public class UserdetailsServices {

    public Connection connection;
    public ResultSet resultset;
//    private Object resultSet;

    public UserdetailsServices() {
        try {
            connection = new ConnectionManager().getConnection();
//here I am getting connection=null.
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(UserdetailsServices.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(UserdetailsServices.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     *
     * @param user
     * @return
     */
    public boolean registerUser(UserModal user) {
        try {
            java.sql.PreparedStatement psmt = connection.prepareStatement("insert into userdetails(role,name,gender,email,password,cpassword,contact) values(?,?,?,?,?,?,?)");
            psmt.setString(1, user.getRole());
            psmt.setString(2, user.getName());
            psmt.setString(3, user.getGender());
            psmt.setString(4, user.getEmail());
            psmt.setString(5, user.getPassword());
            psmt.setString(6, user.getCpassword());
            psmt.setString(6, user.getContact());
            int flag = psmt.executeUpdate();
            if (flag > 0) {
                return true;
            } else {
                return false;
            }
        } catch (SQLException ex) {

            return false;
        }
    }

1 个答案:

答案 0 :(得分:0)

插入有7个字段,但preparaedstatement只设置6个字段。它缺少设置接触值。这就是它给出零错误的原因。

而不是这个

psmt.setString(6, user.getCpassword());
psmt.setString(6, user.getContact());

使用此

psmt.setString(6, user.getCpassword());
psmt.setString(7, user.getContact());