java用addBatch()批量执行sql语句实例

Test .java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Test {
	static Connection con; // 声明Connection对象
	static Statement sql; // 声明Statement对象
	static ResultSet res;
	public Connection getConnection() { // 连接数据库方法
		try {
			Class.forName("net.sourceforge.jtds.jdbc.Driver");
			con = DriverManager.getConnection(
					"jdbc:jtds:sqlserver://127.0.0.1:1433/model", "sa", "0000");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con; // 返回Connection对象
	}
	// //////////////////////////////////
	public static void process1() {
		Test c = new Test();
		con = c.getConnection();
		try {
			sql = con.createStatement();
			sql.addBatch("insert into stu (addr,name,id)values('A','AAA',20);");
			sql.addBatch("insert into stu (addr,name,id)values('B','BBB',20)");
			sql.addBatch("insert into stu (addr,name,id)values('C','CCC',24)");
			sql.addBatch("insert into stu (addr,name,id)values('D','DDD',46)");
			sql.addBatch("insert into stu (addr,name,id)values('E','EEE',20)");
			// 执行批处理语句
			sql.executeBatch();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
/////////////////////////////
Main .java
public class Main {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Test.process1();
		System.out.println("finish");
	}

}


你可能感兴趣的:(java,sql)