向數據庫發送多條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(); } } }