在学习javaweb和servlet写一个项目时出现了空指针异常。经过异常艰难的排查后,发现虽然jdbc连接上了mysql,但是conn返回是null。后来发现应该是jdbc连接方法与jdk、mysql等的版本有关系。
1、我的jdk是1.8,因此compliance要改成对应的(之前我的是1.5,也不知道怎么搞的)。
2、我的mysql是5.5.3,版本较低。因此使用以下连接方式不可行。
static {
try {
Class.forName("com.mysql.jdbc.Driver"); //反射加载
} catch (ClassNotFoundException e) {
System.out.println("mysql初始化失败");
e.printStackTrace();
}
}
//获取链接
public static Connection getConn() {
Connection conn = null; //声明接口
try {
//加载驱动 库
DriverManager.getConnection("jdbc:mysql://localhost:3306/db?user=root&password=root");
System.out.println("success");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("连接失败");
e.printStackTrace();
}
return conn;
}
因此需要使用以下方式(我认为其中代码有些冗余,但是具体不太了解)
public static Connection getConn() {
Connection conn = null; //声明接口
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/ebuys";
String user = "root";
String password = "root";
try {
Class.forName(driver);
try {
conn = DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
System.out.println("连接失败");
e.printStackTrace();
}
finally {
}
return conn;
}