How do to commit or rollback transaction in JDBC?

Executing a database manipulation command such as insert, update or delete can sometime throw exception due to invalid data. To protect the integrity of our application data we must make sure that when a transaction fails we must rollback all the executed queries.

In this example we are using MySQL database. To enable transaction capability in MySQL make sure that you are using InnoDB storage engine to create your databases and tables.

package org.kodejava.jdbc;

import java.math.BigDecimal;
import java.sql.*;

public class TransactionRollbackExample {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        try (Connection conn =
                     DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            conn.setAutoCommit(false);

            String orderQuery = """
                    INSERT INTO purchase_order (username, order_date)
                    VALUES (?, ?)
                    """;

            try (PreparedStatement stmt = conn.prepareStatement(orderQuery,
                    PreparedStatement.RETURN_GENERATED_KEYS)) {
                stmt.setString(1, "jduke");
                stmt.setDate(2, new Date(System.currentTimeMillis()));
                stmt.execute();

                ResultSet keys = stmt.getGeneratedKeys();
                long orderId = 1L;
                if (keys.next()) {
                    orderId = keys.getLong(1);
                }

                // This is an invalid statement that will cause exception to
                // demonstrate a rollback.
                String orderDetailQuery = """
                        INSERT INTO purchase_order_detail (order_id, product_id, quantity, price)
                        VALUES (?, ?, ?, ?)
                        """;

                PreparedStatement detailStmt = conn.prepareStatement(orderDetailQuery);
                detailStmt.setLong(1, orderId);
                detailStmt.setInt(2, 1);
                detailStmt.setInt(3, 10);
                detailStmt.setBigDecimal(4, new BigDecimal("29.99"));
                detailStmt.execute();

                // Commit transaction to mark it as a success database operation
                conn.commit();
                System.out.println("Transaction commit...");
            } catch (SQLException e) {
                // Rollback any database transaction due to exception occurred
                conn.rollback();
                System.out.println("Transaction rollback...");
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

How do I send a cookie in Servlet?

A cookie is a piece of information sent to a browser by a Web Server. The browser then returns that information to the Web server. This is how some Web pages remember your previous visits; for example, an e-commerce website might use a cookie to remember which items you’ve placed in your online shopping cart. Cookies can also store user preference information, login data, etc.

Here is an example to send a cookie in the HTTP response object to the client browser.

package org.kodejava.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "CookieServlet", urlPatterns = "/test-cookie")
public class WriteCookieExample extends HttpServlet {

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");

        // Send a cookie named username to the client. There are some others
        // properties that we can set before we send the cookie, such as comments,
        // domain name, max age, path, a secure flag, etc.
        Cookie cookie = new Cookie("username", "jduke");
        response.addCookie(cookie);
    }
}

Maven dependencies

<!--https://search.maven.org/remotecontent?filepath=javax/servlet/javax.servlet-api/4.0.1/javax.servlet-api-4.0.1.jar-->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
</dependency>

Maven Central

How do I create a connection to MS Access database?

The following example show you how to create a connection to Microsoft Access databases. To allow the database access to be authenticated, the security user account can be added from File -> Info -> Users and Permissions screen.

Just like accessing any other databases in the Java platform we need a JDBC driver. To access Microsoft Access databases we can use UCanAccess, an open-source pure Java JDBC driver for Microsoft Access databases, it allows us to manipulate data in various versions of MS Access databases.

Here what we do in the code snippet below:

  • Prepare USERNAME and PASSWORD that will be used for accessing the database.
  • Define the database JDBC URL which contains the path to MS Access file.
  • Get the connection in try-with-resource statement using the DriverManager.getConnection() method and passes URL, USERNAME, and PASSWORD as arguments.
  • The connection will automatically closed by the try-with-resource when finished.
package org.kodejava.jdbc;

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

public class MSAccessConnect {
    private static final String USERNAME = "admin";
    private static final String PASSWORD = "admin";

    private static final String URL =
            "jdbc:ucanaccess://C:/Users/wayan/Temp/kodejava.mdb;";

    public static void main(String[] args) throws Exception {
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            // Do something with the connection here!
            System.out.println("connection = " + connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

The connection object printed from the code above:

connection = net.ucanaccess.jdbc.UcanaccessConnection@63376bed[C:\Users\wayan\Temp\kodejava.mdb]

Before JDK 8, the sun.jdbc.odbc.JdbcOdbcDriver driver can be used to connect to Microsoft Access databases. On the example below we can either connect through the DSN created previously on the Windows system, or we can create it in our program as the long URL below.

In Microsoft Access 2003, to allow the database access to be authenticated the security user account can be added from Tools -> Security -> User and Group Accounts menu.

package org.kodejava.jdbc;

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

public class MSAccessODBCBridge {
    private static final String USERNAME = "admin";
    private static final String PASSWORD = "admin";
    private static final String DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";

    // If you want to use you ODBC DSN
    //private static final String URL = "jdbc:odbc:TestDB";
    private static final String URL =
            "jdbc:odbc:Driver={MICROSOFT ACCESS DRIVER (*.mdb, *.accdb)};" +
            "DBQ=C:/Users/wayan/Temp/kodejava.mdb;";

    public static void main(String[] args) throws Exception {
        Class.forName(DRIVER);
        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            // Do something with the connection here!
            System.out.println("connection = " + connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

The connection object printed from the code above:

connection = sun.jdbc.odbc.JdbcOdbcConnection@4ec4f498

Maven Dependencies

<dependency>
  <groupId>io.github.spannm</groupId>
  <artifactId>ucanaccess</artifactId>
  <version>5.1.1</version>
</dependency>

How do I calculate process elapsed time?

This example shows us how to use the System.nanoTime() method to get the amount of time a process take place. Please be aware that the nano time value is not related to the real world time value.

package org.kodejava.lang;

public class ElapsedTimeExample {
    public static void main(String[] args) {
        // Get the start time of the process
        long start = System.nanoTime();
        System.out.println("Start: " + start);

        // Just do some a bit long process calculating the total value
        // of even number from zero to 10000
        int totalEven = 0;
        for (int i = 0; i < 10000; i++) {
            if (i % 2 == 0) {
                totalEven = totalEven + i;
            }
        }

        // Get the end time of the process
        long end = System.nanoTime();
        System.out.println("End  : " + end);

        long elapsedTime = end - start;

        // Show how long it took to finish the process
        System.out.println("The process took approximately: "
            + elapsedTime + " nano seconds");
    }
}

And example of the result are:

Start: 35034476484699
End  : 35034477434200
The process took approximately: 949501 nano seconds

How do I create a Hello World Applet?

The code below demonstrate the very basic of Java applet. Applet is a small Java application that can be embedded on the web browser.

package org.kodejava.applet;

import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet {
    public void init() {
    }

    public void start() {
    }

    public void stop() {
    }

    public void destroy() {
    }

    public void paint(Graphics g) {
        g.setColor(Color.GREEN);
        g.drawString("Hello World", 50, 100);
    }
}

To display the applet we need to create an HTML document. Here is a simple example of the document.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Hello World Applet</title>
</head>

<body>
<applet
        code="org.kodejava.applet.HelloWorldApplet"
        height="250"
        width="250">
</applet>
</body>
</html>

You can now load the applet in your browser or by using the appletviewer utility.

appletviewer.exe hello-world-applet.html
** Deprecated: The Applet API is deprecated since JDK 9, no replacement.