import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

public class TestExecuteBatch {
	/* SQL to setup test database
	
	CREATE DATABASE testdb;
	CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'testpassword';
	GRANT ALL PRIVILEGES ON testdb.* TO 'testuser'@'localhost';
	
	USE testdb;
	
	CREATE TABLE table1 (
	    col1 VARCHAR (30)
	);
	
	INSERT INTO table1 (col1) VALUES ('value1');
	INSERT INTO table1 (col1) VALUES ('value2');
	
	 */

	public static void main(String args[]) throws SQLException {
		String jdbcUrl = "jdbc:mariadb://localhost:3306/testdb";
		String username = "testuser";
		String password = "testpassword";
		String query = "UPDATE `table1` SET `col1`=? WHERE `col1`=?";
		int[] updateCounts;

		/* Update two rows in a batch manner */
		try (Connection con = DriverManager.getConnection(jdbcUrl, username, password)) {
			con.setAutoCommit(false);

			try (PreparedStatement ps = con.prepareStatement(query)) {
				ps.setString(1, "valueNew");
				ps.setString(2, "value1");
				ps.addBatch();

				ps.setString(1, "valueNew");
				ps.setString(2, "value2");
				ps.addBatch();

				updateCounts = ps.executeBatch();
				con.commit();
			}
		}

		/* Check for each of the executed queries how many rows have been updated. This should be two. */
		for (int index = 0; index < updateCounts.length; index++) {
			int rowsUpdated = updateCounts[index];

			if (rowsUpdated > 0) {
				/* This works for MariaDB connector 2.7.7; should but does not work for versions between 3.0.0 and 3.1.0 */
				System.out.println("Success: rows updated (should be 1): " + rowsUpdated);
			} else if (rowsUpdated == 0) {
				/* This means no rows have been updated (should not be the case for this example). */
				System.out.println("Success: No rows updated");
			} else if (rowsUpdated == Statement.SUCCESS_NO_INFO) {
				/* This should not happen, but it happens for MariaDB connection versions between 3.0.0 and 3.1.0. */
				System.out.println("Failure: SUCCESS_NO_INFO");
			} else {
				System.out.println("Failure code: " + rowsUpdated);
			}
		}
	}
}