写一个例子:
public class testObject {
public List query(){
//声明连接
Connection conn=null;
List list=new ArrayList();
//声明连接对象
PreparedStatement ps=null;
//声明结果集
ResultSet rs=null;
try {
//连接设置
//驱动加载
Class.forName("oracle.jdbc.driver.OracleDriver");
//url设置
String url="jdbc:oracle:thin:@127.0.0.1:1521:orcl";
//连接数据库
conn=DriverManager.getConnection(url,"test","orcl");
//设置提交为手动
conn.setAutoCommit(false);
//写sql
String sql="select id,date from student where"
+"name like '%李%'";
ps=conn.prepareStatement(sql);
//-----
//替换占位符
//-------
//执行查询
rs=ps.executeQuery();
//如果有数据,继续执行
while(rs.next()){
Object obj=new Object();
stu.setId(rs.getString("id"));
java.sql.Date d=rs.getDate("date");
list.add(stu);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//逆向关闭资源
if(conn!=null){
rs.close();
ps.close();
conn.close();
}
}
return list;
}
}