问题遇到的现象和发生背景
在tomcat运行时,用于连接数据库的这个DB类没有加载,为什么啊
问题相关代码,请勿粘贴截图
运行结果及报错内容
public class DB {
private static Map<String , Book> books=new LinkedHashMap<String, Book>();
static {
//1.注册驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
String url = "jdbc:mysql://localhost:3306/servletshopping";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);
//3.获取数据库操作对象
Statement statement = connection.createStatement();
if (connection == null) {
System.out.println("连接失败");
} else {
System.out.println("连接成功");
}
//4.sql语句
String sql = "Select * from book";
//5.执行语句
ResultSet result = statement.executeQuery(sql);
int i = 1;
while (result.next()) {
String id = result.getString("id");
String name = result.getString("name");
String author = result.getString("author");
int price = result.getInt("price");
books.put(i + "", new Book(id, name, author, price));
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 获得所有图书
public static Collection<Book> getAll() {
return books.values();
}
// 根据id查找图书
public static Book find(String id) {
return books.get(id);
}
}
我的解答思路和尝试过的方法
数据库的连接步骤是没有问题的,能够查询到结果,但就是运行tomcat后,DB类就不加载啦。