一个简单的jdbc程序的小小疑问(先看问题)

来源:百度知道 编辑:UC知道 时间:2024/06/15 05:27:53
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class TestDML {

public static void main(String[] args){
Connection connection = null;
Statement statement = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
connection =
DriverManager.getConnection("jdbc:oracle:thin:" +
"@localhost:1521:ORCL","scott","tiger");
statement = connection.createStatement();
String sql = "insert into dept2 values('20','game','bj')";
statement.executeUpdate(sql);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
finally{
try{
if(connection != null){
connection.close();
connection = nu

finally模块主要是为了释放资源 如你所说:

情形一:
如果connection为null; 说明你在获取连接得时候就已经出现问题了。
首先在第一个 catch (SQLException e) { e.printStackTrace(); }就会捕获异常。然后 finally 必定会执行~ 导致执行connection.close();报错 第二个 catch (SQLException e) { e.printStackTrace(); }捕获异常

情形二:
关闭connection;未进入finally块就关闭了连接;statement.executeUpdate(sql); 后执行connection.close(); 或 finally后马上加上connection.close(); 这样会导致在 if(connection != null){
connection.close();
connection = null;
}
报错。 希望能帮到你。

出现NullPointerException了呗