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

用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 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码