weixin_53249456
2021-09-15 00:58
采纳率: 75%
浏览 171

用idea连接mysql时,出现.NullPointerException异常

这是工具类:

img

private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;

static{
    try{
        InputStream in = jdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(in);

        driver = properties.getProperty("name");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");

        //1.驱动只用加载一次
        Class.forName(driver);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

//获取连接
public static Connection getConnection() throws SQLException {
    return DriverManager.getConnection(url,username,password);
}
//释放连接资源
public static void release(Connection conn, Statement st, ResultSet rs){
    if(rs != null){
        try {
            rs.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    if(st != null){
        try {
            st.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    if(conn != null){
        try {
            conn.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

配置文件db.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=123456

实现代码:
public static void main(String[] args) {

    Connection conn = null;
    Statement st = null;
    ResultSet rs = null;
    try {
        conn = jdbcUtils.getConnection();//获取数据库连接
        st = conn.createStatement();//获得SQL的执行对象
        String sql = "INSERT INTO users(id,`name`,`password`,`email`,`birthday`)" +
                "VALUES(4,'ding','123456','123456789@qq.com','1990-12-28')";
        int i = st.executeUpdate(sql);
        if(i > 0){
            System.out.println("插入成功");
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        jdbcUtils.release(conn,st,rs);
    }
}

然后就是db.properties的位置,在src目录下

img

我找不出问题,但是有空指针异常

img

但是在sqlyog中看到数据确实插入成功了

img

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题