2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > java jdbc 批处理_JDBC的批处理操作

java jdbc 批处理_JDBC的批处理操作

时间:2019-10-26 00:45:18

相关推荐

java jdbc 批处理_JDBC的批处理操作

JDBC的批处理操作

1 什么是JDBC批处理

JDBC批处理,意思是我们可以执行一批(组)SQL操作。批处理可以使数据库执行性能更快。

java.sql.Statement和java.sql.PreparedStatement接口都提供了用于批处理的方法。

2 JDBC批处理的好处

提交数据库执行性能

3 批处理的方法

方法

说明

void addBatch(String query)

将SQL语句添加到批处理中。

int[] executeBatch()

执行批处理中的SQL语句。

4 Statement进行JDBC批处理

4.1 编写测试类

StmtBatchDemo:

package com.yiidian;

import java.io.*;

import java.sql.*;

/**

* 一点教程网 -

*/

public class StmtBatchDemo {

public static void main(String args[])throws Exception {

try {

Class.forName("com.mysql.jdbc.Driver");

Connection con = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/test", "root", "root");

con.setAutoCommit(false);

Statement stmt=con.createStatement();

//把SQL语句加入批处理中

stmt.addBatch("insert into t_user(username,password) values('eric','123')");

stmt.addBatch("insert into t_user(username,password) values('jack','123')");

//执行批处理

stmt.executeBatch();

mit();

con.close();

}catch(Exception e){

System.out.println(e);

}

}

}

4.2 运行测试

5 PreparedStatement进行JDBC批处理

5.1 编写测试类

PsmtBatchDemo:

package com.yiidian;

import java.io.*;

import java.sql.*;

/**

* 一点教程网 -

*/

public class PsmtBatchDemo {

public static void main(String args[])throws Exception {

try {

Class.forName("com.mysql.jdbc.Driver");

Connection con = DriverManager.getConnection(

"jdbc:mysql://localhost:3306/test", "root", "root");

PreparedStatement ps=con.prepareStatement("insert into t_user(username,password) values(?,?)");

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

while(true){

System.out.println("请输入名称");

String name=br.readLine();

System.out.println("请输入密码");

String password=br.readLine();

ps.setString(1,name);

ps.setString(2,password);

//添加到批处理中

ps.addBatch();

System.out.println("想要继续添加记录么? y/n");

String ans=br.readLine();

if(ans.equals("n")){

break;

}

}

//执行批处理操作

ps.executeBatch();

System.out.println("保存成功");

con.close();

}catch(Exception e){

System.out.println(e);

}

}

}

5.2 运行测试

最终数据库表中添加了两条记录

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。