weixin_53249456 2021-09-15 00:58 采纳率: 75%
浏览 312
已结题

用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条回答 默认 最新

  • Roc-xb 后端领域优质创作者 2021-09-15 04:24
    关注

    driver = properties.getProperty("name");
    改成
    driver = properties.getProperty("driver")

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 9月23日
  • 已采纳回答 9月15日
  • 创建了问题 9月15日

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝