关于SQL语句和变量的组合问题

来源:互联网 发布:java web 工作 编辑:程序博客网 时间:2024/05/29 11:48

Hibernate链接数据库

1.直接连接 代码如下

 

String user = "admin";Query q = session.createQuery("from Users u where u.username='" + user + "'");


2.使用占位符 ?或者: 代码如下

 

Query q = session.createQuery("from Users u where u.username=?");q.setParameter(0, "admin");
//占位符是从0开始的

 

区别下和JDBC占位符的区别

方法1没有区别

方法2占位符的起始位置不同

String sql = "select * from books where user = ?";PreparedStatement stm;try {stm = conn.prepareStatement(sql);stm.setString(1, user); ">//占位符是从1开始的ResultSet rs = stm.executeQuery();while(rs.next()){Book book = new Book();book.setBookName(rs.getString("bookname"));book.setUser(rs.getString("user"));books.add(book);}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}


 

原创粉丝点击