带有参数的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:
- public class DBParamTest {
- public static void main(String[] args) {
- StringBuilder sql=new StringBuilder();
- sql.append( "select * from t_corp t where t.corpid=? and t.corpname=? ")
- .append("and t.stamp between to_date(?,'yyyy-mm-dd HH24:mi:ss') and to_date(?,'yyyy-mm-dd HH24:mi:ss')");
- Connection con = null;
- try {
- con = DBTest.getCon();//连接数据库
- } catch (SQLException e) {
- e.printStackTrace();
- return;
- }
- //为sql语句设置参数
- DBParams params = new DBParams();
- params.addParam(1314);
- params.addParam("惠山分局钱桥派出所");
- params.addParam("2010-01-01 00:00:00");
- params.addParam("2010-04-03 03:00:00");
- PreparedStatement pst = null;
- ResultSet rs = null;
- try {
- pst = con.prepareStatement(sql.toString());
- params.prepareStatement(pst);
- rs = pst.executeQuery();
- if(rs.next()){
- System.out.println("remark:" + rs.getString("corpname"));
- System.out.println("stamp:"+rs.getTimestamp("stamp").toString().substring(0, rs.getTimestamp("stamp").toString().length()-2));
- }
- } catch (SQLException e) {
- e.printStackTrace();
- }finally{
- DBUtil.closeRs(rs);
- DBUtil.closePst(pst);
- DBUtil.closeCon(con);
- }
- }
- }