Dipl.-Inf. (FH) T. Mättig


JDBC and auto commit example

Abgelegt unter: — Thiemo Mättig @ 14:04

This Java example inserts a bunch of dummy data into a database using basic JDBC. The example shows the differende between auto commit enabled and disabled.

import java.sql.*;

public class FillDatabase
  public static void main(String[] args)
    //This is a bad example for try and catch because it does not do
      //Use the JDBC or any other driver. Warning! The runntime of
      //this example depends on the database you are using. In
      //some databases (e.g. MySQL 4.0) there is no difference
      //between autoCommit on or off.

      //Here are two example connection strings.
      String url = "jdbc:odbc:MyDatabase";
      //String url = "jdbc:mysql://localhost:3306/test";
      String user = "";
      String password = "";

      //By default, autoCommit is true.
      boolean autoCommit = false;
      //Warning! In MySQL 4.0 there are no transactions.
      //AutoCommit does not make any difference there.

      Connection connection =
        DriverManager.getConnection(url, user, password);

      Statement statement = connection.createStatement();

      //Delete everything first (for demonstration only).
      //statement.execute("DELETE FROM `people`");
      //if (! autoCommit) connection.commit();

      System.out.println("Please wait...");

      for (int i = 0; i < 50; i++)
        System.out.println("Creating row #" + i + "...");

        String firstname = "First " + Math.random();
        String lastname = "Last " + Math.random();
        //Warning! Instead of building a string a
        //PreparedStatement would be much better (and more
        //secure). See connection.prepareStatement().
        String sql = "INSERT INTO " +
          "`people` (`firstname`,         `lastname`)" +
          " VALUES  ('" + firstname + "', '" + lastname + "')";

        //Access may have a bug and does not create all rows.
        //Any SELECT statement helps fixing this issue.
        //statement.executeQuery("SELECT * FROM `people`");

      //Do the commit for all the INSERTs executed above.
      if (! autoCommit) connection.commit();

    catch (Exception e)
      //Bad use of try-catch, but better than nothing.


Noch keine Beiträge.

Einen Kommentar abgeben

Sorry, das Kommentarformular ist derzeit abgeschaltet.

Powered by WordPress