JDBC操作数据库,业务只有几行代码,却要写一大堆异常处理,烦死人。
使用datasource,也是一样要处理异常:
String DBDRIVER = "oracle.jdbc.driver.OracleDriver";
String DBURL = "jdbc:oracle:thin:@localhost:1521:cjlu";
String DBUSER = "scott";
String DBPASSWORD = "tiger";
Connection conn = null;
PreparedStatement ps = null;
ResultSet res=null;
try {
Class.forName(DBDRIVER);
// 连接时必须填写用户名及密码
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASSWORD);
// 查询用户
String sql = "select * from users where username=?";
ps = conn.prepareStatement(sql);
ps.setString(1, "zhangsan");
res=ps.executeQuery();
while(res.next()){
System.out.println(res.getString("username")+res.getString("email"));
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
使用datasource,也是一样要处理异常:
try
{
String JNDINAME = "java:comp/env/jdbc/cjlu" ;
Context ctx= new InitialContext();
DataSource ds=(DataSource)ctx.lookup(JNDINAME);
conn=ds.getConnection();
String sql="select * from users where username=?";
ps=conn.prepareStatement(sql);
ps.setString(1, "zhangsan");
ps.executeQuery();
}