import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringDataSourceTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource=(DataSource)ctx.getBean("dataSource");
Connection con=null;
Statement stmt=null;
ResultSet res=null;
try{
con=dataSource.getConnection();
stmt=con.createStatement();
res=stmt.executeQuery("select * from student");
while(res.next()){
System.out.println(res.getInt("id"));
System.out.println(res.getString("username"));
}
}
catch(SQLException e){
e.printStackTrace();
}
finally{
/*
if(res!=null){
try {
res.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
closeJdbcResource(res);
closeJdbcResource(stmt);
closeJdbcResource(con);
}
}
public static void closeJdbcResource(Object resource){
Class clazz=resource.getClass();
try {
java.lang.reflect.Method method=clazz.getMethod("close", null);
method.invoke(resource, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注释掉的是以前的写法。