Hgj_study
Hgj_study
2019-04-22 22:15

不知道为啥会报:线程“main”java.lang中的异常。无法初始化类JdbcUtil.JDBCUtils的错误?

  • java
  • intellij-idea
package Jdbc;

import JdbcUtil.JDBCUtils;
import domain.user;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcUtilDemo1 {
    public static void main(String[] args) {

            List<user> list = new JdbcUtilDemo1().findAll2();
            System.out.println(list);
            System.out.println(list.size());
        }

    /*
    演示JDBC工具类
     */
    public List<user> findAll2() {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        List<user> list = null;
        try {/*//1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取连接
        connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/eesy_mybatis?useSSL=false&serverTimezone=CTT","root","1799510625hgj");*/
            connection = JDBCUtils.getConnection();
            //3.定义sql
            String sql = "select * from user";
            //4.获取执行sql的对象
            statement = connection.createStatement();
            //5.执行sql
            resultSet = statement.executeQuery(sql);
            //6.遍历结果集,封装对象,装载集合
            user user = null;
            list = new ArrayList<user>();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                Date birthday = resultSet.getDate("birthday");
                String sex = resultSet.getString("sex");
                String address = resultSet.getString("address");
                //创建user对象,并赋值
                user = new user();
                user.setId(id);
                user.setUsername(username);
                user.setBirthday(birthday);
                user.setSex(sex);
                user.setAddress(address);
                //装载集合
                list.add(user);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            //释放资源
       /* if(resultSet != null){
            resultSet.close();
        }
        if(statement != null){
            statement.close();
        }
        if(connection != null){
            connection.close();
        }*/
            JDBCUtils.close(resultSet, statement, connection);
        }
    return list;
    }
}

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

2条回答

为你推荐

换一换