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 block
e.printStackTrace();
}