Mysql
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Mysql

Ví dụ về câu lệnh JDBC - Chèn hàng loạt, cập nhật, xóa

Khi bạn có nhiều lệnh chèn hoặc cập nhật sql để thực thi, bạn có thể sử dụng java.sql.Statement addBatch(String sqlCmd) để nhóm chúng lại với nhau và sau đó chạy java.sql.Statement executeBatch() để cam kết tất cả các lệnh với máy chủ cơ sở dữ liệu cùng một lúc.

Ghi chú về hoạt động hàng loạt của JDBC

  1. Nâng cao hiệu suất giao tiếp cơ sở dữ liệu vì các lệnh sql được gửi đến máy chủ cơ sở dữ liệu theo nhóm, điều này có thể giảm chi phí giao tiếp giữa máy khách và máy chủ.
  2. Hoạt động hàng loạt là một tính năng của máy chủ cơ sở dữ liệu đích, nó không được trình điều khiển jdbc yêu cầu. Bạn có thể sử dụng Connection.getMetaData().supportsBatchUpdates() để kiểm tra xem cơ sở dữ liệu đích có hỗ trợ cập nhật hàng loạt hay không.
  3. Thao tác hàng loạt có thể được sử dụng để không chỉ chèn lệnh mà còn cập nhật và xóa lệnh.
  4. Bạn nên sử dụng java.sql.Connection.setAutoCommit(false) để tắt tự động cam kết cơ sở dữ liệu trước khi thực hiện các hành động db hàng loạt.
  5. Sau khi thực hiện các hoạt động hàng loạt, hãy sử dụng java.sql.Connection.commit() để cam kết các hoạt động với máy chủ cơ sở dữ liệu cùng một lúc.
  6. Bạn nên chạy java.sql.Connection.setAutoCommit(true) để bật cam kết tự động cho các hoạt động db sau này.
  7. Sql theo lô có thể vận hành nhiều bảng.

Đoạn mã SQL hàng loạt

	/* Get connection object. */
	Connection dbConn = this.getMySqlConnection(ip, port, dbName, userName, password);
			
	/* Disable auto commit. */
	dbConn.setAutoCommit(false);
			
	/* Get statement object. */
	Statement stmt = dbConn.createStatement();
		
    /* Add sql in batch, each sql can operate different table. */		
	stmt.addBatch(sql1);
	
	stmt.addBatch(sql2);
	
	stmt.addBatch(sql3);
	
	stmt.addBatch(sql4);
	
	stmt.addBatch(sql5);
	
	stmt.addBatch(sql6);

	/* Execute batch sql to db server. */
	int updateCountArr[] = stmt.executeBatch();
		
    /* Do not forget commit. */		
    dbConn.commit();
		
    /* Enable auto commit for later db operation. */		
    dbConn.setAutoCommit(true);

Hoàn thành mã mẫu

Ví dụ dưới đây sẽ sử dụng cơ sở dữ liệu mysql, chèn và cập nhật dữ liệu vào bảng giáo viên và học sinh hàng loạt. Bạn có thể tham khảo Cách sử dụng JDBC để kết nối cơ sở dữ liệu MySql để tìm hiểu thêm về JDBC MySQL.

	public void testBatchUpdate(String ip, int port, String dbName, String userName, String password)
	{
		String sqlArr[] = new String[6];
		
		sqlArr[0] = "insert into student values('richard','[email protected]')";
		sqlArr[1] = "insert into student values('jerry','[email protected]')";
		sqlArr[2] = "insert into teacher(name, email) values('tom','[email protected]')";
		sqlArr[3] = "update teacher set email = '[email protected]' where name = 'hello'";
		sqlArr[4] = "insert into teacher(name, email) values('song','[email protected]')";
		sqlArr[5] = "insert into teacher(name, email) values('jerry','[email protected]')";
		
		this.executeBatchSql(ip, port, dbName, userName, password, sqlArr);
	}
	
	/* Batch execute insert, update, delete commands. */
	public void executeBatchSql(String ip, int port, String dbName, String userName, String password, String sqlArr[])
	{
		/* Declare the connection and statement object. */
		Connection dbConn = null;
		Statement stmt = null;
		try
		{
			/* Get connection object. */
			dbConn = this.getMySqlConnection(ip, port, dbName, userName, password);
			
			/* Check whether this db support batch update or not. */
			boolean supportBatch = dbConn.getMetaData().supportsBatchUpdates();
			if(supportBatch)
			{
				System.out.println("This database support batch update.");
			}else
			{
				System.out.println("This database do not support batch update.");
			}
			
			
			/* Disable auto commit. */
			dbConn.setAutoCommit(false);
			
			/* Get statement object. */
			stmt = dbConn.createStatement();
			
			if(sqlArr!=null)
			{
				int len = sqlArr.length;
				for(int i=0;i<len;i++) { String sql = sqlArr[i]; stmt.addBatch(sql); System.out.println("Batch add sql : " + sql); } if(len > 0)
				{
					/* The return array save each command updated rows number. */
					int updateCountArr[] = stmt.executeBatch();
					
				    dbConn.commit();
				    
				    dbConn.setAutoCommit(true);
					
					System.out.println("Execute batch sql successfully. ");
					
					int updateLength = updateCountArr.length;
					
					for(int j=0 ; j < updateLength; j++)
					{
						int updateCount = updateCountArr[j];
						System.out.println("updateCount : " + updateCount);
					}
				}
			}
		}catch(Exception ex)
		{
			ex.printStackTrace();
		}finally
		{
			this.closeDBResource(stmt, dbConn);
		}
	}

	public static void main(String[] args) {
		
		/* Below are db connection required data. */
		String ip = "localhost";
		int port = 3306;
		String dbName = "test";
		String userName = "root";
		String password = "";
		
		/* Create an instance. */
		JDBCStatementExample jdbcStatementExample = new JDBCStatementExample();
		jdbcStatementExample.testBatchUpdate(ip, port, dbName, userName, password);
	}

Mã nguồn:

  1. [tải xuống id =”2551 ″]

  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Sử dụng câu lệnh IF trong truy vấn MySQL SELECT

  2. Cách nhập dữ liệu từ tệp văn bản vào cơ sở dữ liệu mysql

  3. Thay thế chuỗi MySQL

  4. Tìm kiếm toàn văn bản đơn giản? Dùng thử MySQL InnoDB + CakePHP với Word Stemming

  5. chia nhỏ từ khóa cho bài php mysql