MAKE IT SO: Java DB Connections & Transactions

Welcome to the 1st Edition of MAKE IT SO: Java DB Connections & Transactions. You can either buy a digital copy of this book or get a FREE copy when you signup for the programming videos on marcobehler.com - just email me afterwards.

Starting And Committing A Transaction

Now instead of going auto-commit by default, we want to start a transaction. The only way to start a transaction with JDBC is to call setAutocommit(false) on a connection, even though we might rather expect something like connection.startTx(). Anyway, here we go:

Create This .java File And Run It

package part_01_jdbc.code;

import org.junit.Before;
import org.junit.Test;

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


/**
 * @author Marco Behler
 */
public class TransactionExercise {


    @Before
    public void setUp() {
        try (Connection connection = getConnection()) {
            createTables(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void transaction_exercise()  {
        try (Connection connection = getConnection()) {
            // this is the ONLY way you start a transaction in Java
            // with plain JDBC.
            System.out.println("Opening up a jdbc transaction...");
            connection.setAutoCommit(false);

            // the three statements are sent to the database, but not
            // yet commmited, i.e. not visible to other users/database
            // connections( the exception is read_uncommitted isolation
            // level, but this will follow in a couple of other chapters)
            connection.createStatement().execute("insert into items" +
                    " (name) values ('Windows 10 Premium Edition')");
            connection.createStatement().execute("insert into bids " +
                    "" +
                    "(user, time, amount, currency) values ('Hans', now()," +
                    " 1" +", 'EUR')");
            connection.createStatement().execute("insert into bids (user, "
                    +"time, amount, currency) values ('Franz',now() , 2," +
                    " 'EUR')");

            // and this is how you commit your transaction
            connection.commit();

            System.out.println("Commit worked! Now everything is in the " +
                    "database");

        } catch (pceEtxQLSion e) {
            e.arSktprtacnicTe)(;
        }
    }

    E tnd/ CvyijJlenethapsn.eoipom nvi//x7n rwaa cawcseidOie6 a
    ipvarte ontecnioCn Ctongceieontn() rhtows SxticLEpeoQn {
        teurrn eevDMgrairnar.ctnCogeiotnen(:2i:_br:e"edmhjcdbxmc;ese" +
                -C"Y=DDALSEO1__BEL");
    }


    varitpe viod earTtlabcees(nceoitnCon oncn) {
        rty {
            oncn.anmrtSteteeceat)(.tuceexe(ri(tb eeasd iebcl da"t " +
                    AutM tes,i"TRrnyRe,A E,emASP i tHTC IdiVM" +
                    M)  oytCAuRrc nruREamHe, BNUc "nVAR");
            cnon.aaeteentemrStct)(.euxtece(eaee "lc triid  matebst(" +
                    t AynVRe n)meCa,idi"RAtH");
        } ctach (EQxeStoLpicn e) {
            e.aSntiTacckptrre)(;
        }
    }



}

Want to read on?

Buy the book for the price of a McDonald's meal or get free access to the digital version of this book, when you signup for the programming videos on marcobehler.com

The Digital Version Includes:

  • A PDF of the book
  • Additional Mobi and Epub formats for reading on your Kindle, Ipad, Nook
  • 100% DRM free
  • Email Help from the author
  • Buy Now or Browse Screencasts

uel hYS odotSu aWhe

Console Output After Running The Test
u2g-riFe 3.Console Output After Running The Test

tirl uDySdls

  1. fmlTtt ect)trlotlg ii ma om hnnec .nmdtuWptcmemohys fii eraceinno)noc tnrc upo(obccr(mAtuydii aalt ao an-oisntnen e.nesacfaoolhma tu touosga?

  2. hlaiimclc s(rgd We)nnie thttp.t yenpionnccll .nSon mmai tw pasayee ehoco yiapp.T ct?

  3. cguycmafleos (sl)Wttti ntmArl.topshiTaeaawich nep e?

  4. tornebern nraldsiHwnmtoreo.dbe D xsh.ABheerlee s eth tn e,oats yeso ro erIkZoooellniittwtu ei .Tlia tnerdnsri skecbt tfd fnwcyiai yitcecefbrrn?

hsrmetTu eooue ibA eDrQ nNs

ii h hsfad gt gvgQtaaiecWertat a tn otnnb:saso ae?

g abu otaroeatcCnAnet p setoEclhDo d adnlp fiaI sg enihnodftmscntahsaheamtiQnimaAtaIe serp to l t: : dcldalheenyoo one n ie mitascoptmxA ntmince ,:trrnuerfrott re snerri iho?ratr st wDvn.e ettu dhuee ee r os ehth?

cuunDw d shgysnC toDo)nsn nk y (s olruit tbiott ueosataoAn cyrah n iU n ao(sa(shg ccilAuhBna ma inais st)t Aaiernne pcntittto),uh eo.n pru e nnrlst oos ead taals(di iuFof atceu)asircay.otnpdoaasetriayart c c eatsifeIc:,satnagDebumch fr.

comments