[javaSE] JDBC的批处理

向数据库发送多条sql语句

create database batch

use batch

create table batch_table(

id int primary key auto_increment,

name varchar(20)

)

insert into batch_table values(null,”aaa”)

insert into batch_table values(null,”bbb”)

insert into batch_table values(null,”ccc”)

Statement方式执行批处理:

优点:可以执行多条不同结构的sql语句

缺点:没有使用预编译机制,效率低下

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement; public class JDBCBatchTest {
public static void main(String[] args) {
try {
// 注册数据库驱动
//DriverManager.registerDriver(new Driver());
//使用反射的方式
Class.forName("com.mysql.jdbc.Driver");
//获取数据库连接,导包的时候,注意要导java.sql下的,面向接口编程
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/java","root","root");
//获取传输器对象
Statement statement=conn.createStatement();
statement.addBatch("create database batch");
statement.addBatch("use batch");
statement.addBatch("create table batch_table(id int primary key auto_increment,name varchar(20))");
statement.addBatch("insert into batch_table values(null,'aaa')");
statement.addBatch("insert into batch_table values(null,'bbb')");
statement.addBatch("insert into batch_table values(null,'ccc')");
statement.executeBatch();
} catch (Exception e) {
e.printStackTrace();
}
}
}
上一篇:Maven概念模型


下一篇:[OJ] Find Minimum in Rotated Sorted Array II