/** 注意:良好的编程习惯是尽量的写try-catch-finally
* 而不是一味的throws Exception
* 否则如果在一个大的方法体上写throws Exception,内部出现Exception时
* 有可能导致程序停滞直到耗尽内存。
*/
import java.sql.*;
public class TestJDBC {
public static void main(String[] args) {
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try {//良好的编程习惯是尽量写try-catch-finally
Class.forName("oracle.jdbc.driver.OracleDriver");
//new oracle.jdbc.driver.OracleDriver();
conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.1:1521:SXT", "scott", "tiger");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from dept");
while(rs.next()) {
System.out.println(rs.getString("deptno"));
System.out.println(rs.getInt("deptno"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs != null) {//在JDBC关闭过程中仍然有关闭异常需要捕捉
rs.close(); //首先判断某对象已被成功初始化,即!=null,然后关闭
rs = null; //关闭后还需要将其设置回初始化的null值
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
No comments:
Post a Comment