您的位置:首页 > 编程语言 > Java开发

使用JAVA语言中的addBatch和executeBatch()实现数据批处理插入数据库

2009-11-28 00:55 1051 查看
import java.io.FileReader;

import java.io.BufferedReader;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

import java.sql.Statement;

import javax.naming.InitialContext;

import javax.naming.NamingException;

import javax.sql.DataSource;

public class InertDB_batch {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

System.out.println("***************");

String buf = null;

BufferedReader in = null;

Statement stmt =null;

Connection con =null;

try{

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

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?characterEncoding=gb2312", "root", "root");

stmt = con.createStatement();

}catch(Exception e){

e.printStackTrace();

}

try {

in = new BufferedReader(new FileReader("insert.sql"));

buf = in.readLine();

System.out.println(buf);

} catch (FileNotFoundException e) {

new Exception("insert.sql File not exists!");

} catch (IOException e) {

e.printStackTrace();

}

while (buf != null) {

System.out.println(buf);

try {

//将给定的 SQL 命令添加到此 Statement 对象的当前命令列表中

stmt.addBatch(buf);

buf = in.readLine();

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

try{

int []line = stmt.executeBatch();


for(int i=0;i<line.length;i++){

System.out.println("i = "+i);

}

//System.out.println(line);

}catch(Exception ex){

ex.printStackTrace();

}

System.out.println("***************");

System.out.println("完了!!");

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐