JDBC的批量处理

JDBC的批量处理

批量处理出现的原因:

Statement的execute()等方法一次只能执行一条SQL语句,如果有多条SQL语句要执行的话,可以使用addBatch()方法将要执行的SQL语句加进来,然后执行executeBatch方法,就可以在调用中执行多条语句,提高效率

批量处理的代码:

public static void main(String[] args) {

Connection con = null;

Statement stat = null;

/*try {

con = JdbcUtil.getConnection();

stat = con.createStatement();

stat.addBatch("insert into student(name) values(王五)");

stat.addBatch("insert into student(name) values(王五)");

stat.executeBatch();//批量的操作

} catch (SQLException e) {

e.printStackTrace();

}

JdbcUtil.release1(null, stat, con);*/

使用预处理的批量

PreparedStatement pst = null;

try {

con = JdbcUtil.getConnection();

//在批量中只能执行

pst = con.prepareStatement("insert into student(name) values(?)");

//插入多条语句,通过循环的方式解决

List<Student> list = new ArrayList<Student>();

for(int i=0;i<=5;i++){

Student s = new Student();

list.add(s);

}

for(Student s:list){

pst.setString(1, s.getName());//给占位符赋值

pst.addBatch();//把 数据放到批中

}

pst.executeBatch();//提交批处理

} catch (SQLException e) {

e.printStackTrace();

}

设置生成的语句参数可以指定结果集中是敏感的结果集和可更新的结果集

try {

Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, 敏感的结果集

ResultSet.CONCUR_UPDATABLE); 可更新的结果集 ResultSet rs = st.executeQuery("select * from student");

if(rs.next()){

rs.getObject(1);//定位游标,为第一行

rs.updateString(2, "Tom");//修改的是第二列

rs.updateRow();//提交修改

}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

读取结果集中的属性

public static void main(String[] args) {

Connection con = null;

//结果集的源数据的获取

Statement st = null;

ResultSet res =null;

ResultSetMetaData resmd = null;

try {

con= JdbcUtil.getConnection();

st = con.createStatement();

res = st.executeQuery("select * from student");

resmd = res.getMetaData();

System.out.println(resmd.getColumnCount());//获取有多少列

//获取每一列的列名

for(int i=1;i<=resmd.getColumnCount();i++){

System.out.println(resmd.getColumnLabel(i)+"\t");

}

//获取每一列的类型

for(int i=1;i<=resmd.getColumnCount();i++){

System.out.println(resmd.getColumnType(i)+"\t");

}

/*con = JdbcUtil.getConnection();

DatabaseMetaData dmd =(DatabaseMetaData) con.getMetaData();//获取到所连数据库的数据

System.out.println(dmd.getDatabaseProductName());

System.out.println(dmd.getDriverName());//获取 数据库的名称

System.out.println(dmd.getDatabaseMajorVersion());//获取数据库的版本号

*/ } catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

JdbcUtil.release(null, null, con);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值