// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package tx.nonxadb.jdbc;

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

public class StandardTransaction extends DB {
	@Override
	public Connection getConnection() throws SQLException {
		return DriverManager.getConnection("jdbc:mysql://localhost/Test", "root", "hemmeligt");
	}
	@Override
	public void test() throws SQLException {
		for(int i = 0; i < 10; i++) {
			try(Connection con = getConnection()) {
				con.setAutoCommit(false); // required
				try {
					// implicit begin
					try(Statement stmt = con.createStatement()) {
						stmt.executeUpdate("UPDATE tblsrc SET val = val - 1 WHERE id = 1");
						if(i % 2 != 0) throw new Problem();
						stmt.executeUpdate("UPDATE tbltrg SET val = val + 1 WHERE id = 1");
					}
					con.commit();
				} catch(Problem ex) {
					con.rollback();
					System.out.println("Problem");
				}
			}
		}
	}
	public static void main(String[] args) throws SQLException {
		demo(new StandardTransaction());
	}
}
