JAvaは完璧なJDBCデータベースアクセスを比較する
比較的完璧なデータベース・アクセスの例
package com.jdbc.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PerfectJDBC {
public static void main(String[] args){
String url ="jdbc:oracle:thin:@192.168.1.101:1521:orcl"; //
String username = "scott"; //
String password = "tiger"; //
Connection con = null;
Statement stmt = null;
ResultSet rs=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
//new oracle.jdbc.driver.OracleDriver();
con=DriverManager.getConnection(url,username,password);
stmt= con.createStatement(); //
rs = stmt.executeQuery("select * from emp"); //
while(rs.next()){
System.out.println(rs.getString("ename"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace(); //log4j
}catch(SQLException e){
e.printStackTrace();
}
finally{
try {
if(con!=null){
con.close();
con=null;
}
if(stmt!=null){
stmt.close();
stmt=null;
}
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}