Apache Derby Snippets

  • Post author:
  • Post category:Java

Here are some quick code snippets to help you get started with embedded Apache Derby.

1. If you use Maven, add the Derby dependency.

    <dependency>
    	<groupId>org.apache.derby</groupId>
    	<artifactId>derby</artifactId>
    	<version>10.8.1.2</version>
    </dependency>

2. Connecting to Derby works the same way as other databases. You need the JDBC driver and the database connection URL. Notice create=true in the database URL, which tells Derby to create the database if it does not exist.

	private final static String DB_DRIVER = "org.apache.derby.jdbc.EmbeddedDriver";
	private final static String DB_NAME = "sampleDb";
	private final static String DB_URL = String.format("jdbc:derby:%s;create=true", DB_NAME);

3. Calling Class.forName(DB_URL).newInstance(); will start Derby. To shutdown Derby, run the following function.

	private static void shutdownDerby() {
		try {
			DriverManager.getConnection("jdbc:derby:;shutdown=true");
		} catch (SQLException e) {
			if (((e.getErrorCode() == 50000) && ("XJ015".equals(e.getSQLState())))) {
				// normal shutdown
			} else {
				LOGGER.log(Level.WARNING, e.getMessage(), e);
			}
		}
	}

According to the Apache Derby documentation:

A clean shutdown performs a checkpoint and releases resources. If an embedded application doesn’t shut down Derby, a checkpoint won’t be performed. Nothing bad will happen; it just means that the next connection will be slower because Derby will run its recovery code.

4. To check if a Derby table exists, use DatabaseMetaData.

	public static boolean tableExists(Connection conn, String tableName) {
		boolean tableExists = false;

		ResultSet rs = null;
		try {
			DatabaseMetaData meta = conn.getMetaData();
			rs = meta.getTables(null, null, null, new String[] { "TABLE" });
			while (rs.next()) {
				String currentTableName = rs.getString("TABLE_NAME");
				if (currentTableName.equalsIgnoreCase(tableName)) {
					tableExists = true;
				}
			}
		} catch (SQLException e) {
			LOGGER.log(Level.SEVERE, e.getMessage(), e);
		} finally {
			DbUtils.closeQuietly(rs); // Apache Commons DbUtils
		}

		return tableExists;
	}