001package edu.pdx.cs.joy.jdbc; 002 003import java.io.File; 004import java.sql.Connection; 005import java.sql.DriverManager; 006import java.sql.SQLException; 007 008/** 009 * Helper class for creating connections to H2 databases. 010 * Provides factory methods for both in-memory and file-based H2 databases. 011 */ 012public class H2DatabaseHelper { 013 014 /** 015 * Creates a connection to an in-memory H2 database. 016 * The database will persist as long as at least one connection remains open 017 * due to the DB_CLOSE_DELAY=-1 parameter. 018 * 019 * @param databaseName the name of the in-memory database 020 * @return a connection to the in-memory H2 database 021 * @throws SQLException if a database error occurs 022 */ 023 public static Connection createInMemoryConnection(String databaseName) throws SQLException { 024 return DriverManager.getConnection("jdbc:h2:mem:" + databaseName + ";DB_CLOSE_DELAY=-1"); 025 } 026 027 /** 028 * Creates a connection to a file-based H2 database. 029 * The database will be persisted to a file at the specified path. 030 * 031 * @param databaseFilesDirectory the database file (without the .mv.db extension) 032 * @return a connection to the file-based H2 database 033 * @throws SQLException if a database error occurs 034 */ 035 public static Connection createFileBasedConnection(File databaseFilesDirectory) throws SQLException { 036 return DriverManager.getConnection("jdbc:h2:" + databaseFilesDirectory.getAbsolutePath()); 037 } 038}