带有参数的hql或sql语句

HQL:

     from Student s where s.age>:age

 hibernateTemplate.getSessionFactory().openSession().createQuery(hql).setInt("age",15);

     from student s where s.id in (:ids)

 hibernateTemplate.getSessionFactory().openSession().createQuery(hql).setParameterList("ids",new integer[]{100,102}); 

 

SQL:

 

    1. public class DBParamTest {  
    2.     public static void main(String[] args) {      
    3.         StringBuilder sql=new StringBuilder();  
    4.          sql.append( "select * from t_corp t where t.corpid=? and t.corpname=? ")  
    5.          .append("and t.stamp between to_date(?,'yyyy-mm-dd HH24:mi:ss') and to_date(?,'yyyy-mm-dd HH24:mi:ss')");  
    6.           
    7.         Connection con = null;  
    8.         try {  
    9.             con = DBTest.getCon();//连接数据库  
    10.         } catch (SQLException e) {  
    11.             e.printStackTrace();  
    12.             return;  
    13.         }  
    14.         //为sql语句设置参数  
    15.         DBParams params = new DBParams();  
    16.         params.addParam(1314);  
    17.         params.addParam("惠山分局钱桥派出所");  
    18.         params.addParam("2010-01-01 00:00:00");  
    19.         params.addParam("2010-04-03 03:00:00");  
    20.   
    21.         PreparedStatement pst = null;  
    22.         ResultSet rs = null;  
    23.         try {  
    24.             pst = con.prepareStatement(sql.toString());  
    25.             params.prepareStatement(pst);  
    26.             rs = pst.executeQuery();  
    27.             if(rs.next()){  
    28.                 System.out.println("remark:" + rs.getString("corpname"));  
    29.                 System.out.println("stamp:"+rs.getTimestamp("stamp").toString().substring(0, rs.getTimestamp("stamp").toString().length()-2));  
    30.                   
    31.             }  
    32.         } catch (SQLException e) {  
    33.             e.printStackTrace();  
    34.         }finally{  
    35.             DBUtil.closeRs(rs);  
    36.             DBUtil.closePst(pst);  
    37.             DBUtil.closeCon(con);  
    38.         }  
    39.     }  

posted @ 2013-03-18 11:06  panlovestan  阅读(302)  评论(0编辑  收藏  举报