WeCodeAcademy

Step 6: The database and transactions

Memory is lost when the program stops, so real accounts live in a database. A database enforces rules for you: CHECK (cents >= 0) makes a negative balance impossible, and REFERENCES makes a transfer point at real accounts. Most importantly, a transaction groups statements so that they succeed or fail together (the database's version of step 4). BEGIN ... COMMIT applies them; ROLLBACK throws them away.

Examplesql
Open in editor »

Now watch what the database does when a rule would be broken. The next block tries a change and rolls it back, leaving the data exactly as before:

Examplesql
Open in editor »

In your Java code you would run these through JDBC: connection.setAutoCommit(false), then the updates, then commit(), with rollback() in the catch block. Always use prepared statements with ? parameters.

Quick check

What does ROLLBACK do?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.