Java:尝试捕获MySQL异常
从Java连接到MySQL时遇到错误,因此我将连接建立包装在Java:尝试捕获MySQL异常,java,mysql,Java,Mysql,从Java连接到MySQL时遇到错误,因此我将连接建立包装在try语句中。但是,这样做意味着任何尝试使用连接变量之后都会抛出一个变量conn可能尚未初始化错误。 正确的方法是什么? 我所拥有的: Connection conn; try { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "alexis","pass"); } catch (SQLException e) { S
try
语句中。但是,这样做意味着任何尝试使用连接
变量之后都会抛出一个变量conn可能尚未初始化
错误。
正确的方法是什么?
我所拥有的:
Connection conn;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "alexis","pass");
}
catch (SQLException e) {
System.err.println("SQL exception: " + e.getMessage());
System.exit(1);
}
if (!conn.isClosed()) {
conn.close();
}
错误:
> variable conn might not have been initialized
您应该这样声明您的对象:
Connection conn = null;
然后在使用它之前确保它不为空:
if (conn != null && !conn.isClosed()) {
conn.close();
}
代码:
或者,您可以使用try with resources自动关闭连接
try (Connection conn = DriverManager.getConnection(CONNECTION_URL);
PreparedStatement ps = con.prepareStatement(sqlStrQuery);){
// execution code here..
}catch(SQLException sqle){
// do something
}
变量con可以在try/catch之外访问,但编译器足够聪明,可以识别con可能永远不会被赋值,甚至可能不会为null。局部变量不像实例变量那样自动为空。 解决这个问题最简单的方法就是改变
Connection con;
到
try (Connection conn = DriverManager.getConnection(CONNECTION_URL);
PreparedStatement ps = con.prepareStatement(sqlStrQuery);){
// execution code here..
}catch(SQLException sqle){
// do something
}
Connection con;
Connection con = null;