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

26.04.2005

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
    //anything.
    try
    {
      //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.
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      //Class.forName("com.mysql.jdbc.Driver");

      //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);
      connection.setAutoCommit(autoCommit);

      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 + "')";
        statement.executeUpdate(sql);

        //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();

      System.out.println("Done!");
    }
    catch (Exception e)
    {
      //Bad use of try-catch, but better than nothing.
      System.out.println(e);
    }
  }
}

Kommentare »

Noch keine Beiträge.

Einen Kommentar abgeben

E-Mail-Adresse wird nicht angezeigt, HTML erlaubt: <a href=""> <blockquote> <code> <em> <li> <ol> <strong> <ul>


Powered by WordPress