JDBC 批处理_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > JDBC 批处理

JDBC 批处理

 2014/11/7 0:17:06  huangqiqing123  程序员俱乐部  我要评论(0)
  • 摘要:importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.PreparedStatement;importjava.sql.Statement;publicclassTest{publicstaticConnectiongetConnection(){try{Class.forName("com.mysql.jdbc.Driver");Connectioncon=DriverManager
  • 标签:
class="java" name="code">import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;


public class Test {

	public static Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/uc2", "root", "");
			return con;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 使用 Statement 执行批处理
	 * 批处理只能执行更新类SQL,类似 executeUpdate()
	 */
	public static void statementBatch(){
		Connection con = getConnection();
		Statement st = null;
		if(con != null){
			try {
				st = con.createStatement();
				st.addBatch("INSERT INTO uc_role (role_id, name, note, type ) VALUES ( 1, '1', '1', '1' )");
				st.addBatch("INSERT INTO uc_role (role_id, name, note, type ) VALUES ( 2, '2', '2', '2' )");
				st.addBatch("delete from uc_role where role_id in(1,2)");
				int[] res = st.executeBatch();
				for (int i = 0; i < res.length; i++) {

					//打印结果: 1  1  2
					System.out.println(res[i]);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				//关闭 statement  connection
			}
		}
	}
	
	/**
	 * 使用 PreparedStatement 执行批处理
	 * 批处理只能执行更新类SQL,类似 executeUpdate()
	 */
	public static void preparedstatementBatch(){
		Connection con = getConnection();
		PreparedStatement pst = null;
		if(con != null){
			try {
				pst = con.prepareStatement("INSERT INTO uc_role (role_id, name, note, type ) VALUES ( ?, ?, ?, ? )");
				pst.setInt(1, 1);
				pst.setString(2, "角色1");
				pst.setString(3, "note1");
				pst.setString(4, "type1");
				pst.addBatch();
				
				pst.setInt(1, 11);
				pst.setString(2, "角色11");
				pst.setString(3, "note11");
				pst.setString(4, "type11");
				pst.addBatch();
				
				pst.addBatch("INSERT INTO uc_role (role_id, name, note, type ) VALUES ( 2, '2', '2', '2' )");
				
				pst.addBatch("delete from uc_role where role_id in(1,11,2)");
				
				int[] res = pst.executeBatch();
				for (int i = 0; i < res.length; i++) {

					//打印结果: 1  1  1   3
					System.out.println(res[i]);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				//关闭 preparedstatement  connection
			}
		}
	}
	
	public static void main(String[] args) {
		statementBatch();
		preparedstatementBatch();
	}
}

?

  • 相关文章
发表评论
用户名: 匿名