1.Hibernate 中使用jdbc批量更新
tx = session.beginTransaction();
Connection con=session.connection();
PreparedStatement stmt=con.prepareStatement("update CUSTOMERS set AGE=AGE+1 "
+"where AGE>0 ");
stmt.executeUpdate();
tx.commit();
jdbc批量插入方法1
PreparedStatement psmt=conn.perparedStatement("insert into tablename values(?)");
psmt.setString(0,"aaa");
psmt.addBatch();
psmt.setString(0,"bbb");
psmt.addBatch(0,"aaa");
psmt.executeBatch();
jdbc批量插入方法2
JDBC 批量插入记录
Statement:提供addBatch(String sql) 和 excuteBatch()方法批量更新数据
Statement smt=smt.addBatch("insert into talbename...");
smt.addBatch("sql 语句2");
smt.addBatch("sql 语句3);
smt.executeBatch(); //批量执行
jdbc查询
package chap1;
import java.sql.*;
public class JdbcTest {
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost/test";
Connection con=DriverManager.getConnection(url,"root","root");
String sql="select * from test where userid=?";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1,"123");
ResultSet rs=ps.executeQuery();
while(rs.next()){
String name=rs.getString("username");
int age=rs.getInt(3); //这里的“3”指数据表中的第3个字段的值
System.out.println(name);
System.out.println(age);
}
rs.close();
con.close();
}catch(SQLException e){
System.out.println("Error"+e);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
2.Hibernate 3.0批量更新
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlUpdate = "update Customer set name = :newName where name = :oldName";
int updatedEntities = s.createQuery( hqlUpdate )
.setString( "newName", newName )
.setString( "oldName", oldName )
.executeUpdate();
tx.commit();
session.close();
3.Hibernate 3.0批量删除
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
String hqlDelete = "delete Customer where name = :oldName";
int deletedEntities = s.createQuery( hqlDelete )
.setString( "oldName", oldName )
.executeUpdate();
tx.commit();
session.close();