您的位置:首页 > 数据库

JDBC:用Batch处理多个SQL(SXT)

2008-10-20 11:42 281 查看
JDBC:用Batch处理多个SQL(SXT)

Demo

import java.sql.*;

public class TestBatch

{

/**

* @用Batch处理多个SQL

*/

public static void main(String[] args)

{

// 1.不用PreparedStatement

/*

* Connection conn = null; Statement stmt = null; String url =

* "jdbc:mysql://localhost:3306/college"; String user = "root"; String

* password = "123456";

*

* try { Class.forName("com.mysql.jdbc.Driver"); conn =

* DriverManager.getConnection(url, user, password); stmt =

* conn.createStatement(); stmt.addBatch("insert into user

* values(301,'go1','123','0')"); stmt.addBatch("insert into user

* values(302,'go2','1234','00')"); stmt.addBatch("insert into user

* values(303,'go3','12345','000')");

*

* stmt.executeBatch();

* } catch (ClassNotFoundException e) { // TODO Auto-generated catch

* block e.printStackTrace(); } catch (SQLException e) { // TODO

* Auto-generated catch block e.printStackTrace(); } finally { try {

* if(stmt != null) { stmt.close(); stmt = null; } if(conn != null) {

* conn.close(); conn = null;

* }

* } catch (SQLException e) { // TODO Auto-generated catch block

* e.printStackTrace(); } }

* }

*/

// 2.用PreparedStatement处理

Connection conn = null;

PreparedStatement pstmt = null;

String url = "jdbc:mysql://localhost:3306/college";

String user = "root";

String password = "123456";

try

{

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

conn = DriverManager.getConnection(url, user, password);

pstmt = conn.prepareStatement("insert into user values(?,?,?,?)");

pstmt.setInt(1, 401);

pstmt.setString(2, "goo1");

pstmt.setString(3, "a1");

pstmt.setString(4, "k1");

pstmt.addBatch();

pstmt.setInt(1, 402);

pstmt.setString(2, "goo2");

pstmt.setString(3, "a2");

pstmt.setString(4, "k2");

pstmt.addBatch();

pstmt.setInt(1, 403);

pstmt.setString(2, "goo3");

pstmt.setString(3, "a3");

pstmt.setString(4, "k3");

pstmt.addBatch();

pstmt.executeBatch();

} catch (ClassNotFoundException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

} catch (SQLException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

} finally

{

try

{

if (pstmt != null)

{

pstmt.close();

pstmt = null;

}

if (conn != null)

{

conn.close();

conn = null;

}

} catch (SQLException e)

{

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

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