The Database Access Tutorial uses a flexible configuration system based on config.ini files and Java Properties API to manage database connections. This approach allows switching between different database systems (HSQLDB and H2) without modifying the source code.
The DB_Enterprise.java class demonstrates the fundamental configuration pattern:
Loading Configuration
Building Connection URL
Establishing Connection
DB_Enterprise.java:22-48
File f = new File("config.ini");Properties properties = new Properties();/* Si existe nuestro fichero config.ini cargaremos nuestro archivo y lo cargaremos en nuestra base de datos */if (!f.exists()) { /* Si nuestro archivo no existe lo creamos añadiendo dos propeiedades para cada driver que usaremos */ properties.setProperty("driverH2", "h2"); properties.setProperty("driverHSQLDB", "hsqldb"); /* Añadimos otros 2 setProperty para poner en el nombre de la base de datos */ properties.setProperty("nameDB", "SA"); /* Almacenamos las propiedades a un archivo config.ini para usarlo despues para aplicar las configuraciones */ properties.store(new FileOutputStream("config.ini"), "Configuracion de la base de datos");} else { /* Almacenamos en variables las propiedades de nuestro archivo de configuracion externo */ properties.load(new FileInputStream(f)); driverHSQLDB = properties.getProperty("driverHSQLDB"); driverH2 = properties.getProperty("driverH2"); nameDB = properties.getProperty("nameDB");}
DB_Enterprise.java:50-58
/* Comparamos dependiendo de que gestor de base de datos se use sera diferente su urlpara ser usada en la conexion */if (driverHSQLDB.equals("hsqldb")) { url = "jdbc:hsqldb:file:/home/alumno/Escritorio/BBDD/db_empresa;shutdown=true;hsqldb.lock_file=false"; }else if (driverH2.equals("h2")) { url = "jdbc:h2:file:./db_empresa_h2;AUTO_SERVER=TRUE;DB_CLOSE_DELAY=-1"; }
DB_Enterprise.java:59-65
try{ /* Creamos la conexion de nuestra BBDD con la url con el nombre de usuario y su password*/ Connection conn = DriverManager.getConnection(url, "SA", ""); System.out.println("La conexion se realizo correctamente " + url);}catch(SQLException e){ e.printStackTrace();}
The H2 implementation uses a simpler, hardcoded URL with specific H2 optimizations:
DB_EnterpriseH2.java:7-10
private static final String URL = "jdbc:h2:file:./db_empresa_h2;AUTO_SERVER=TRUE;DB_CLOSE_DELAY=-1";private static final String USER = "SA";private static final String PASSWORD = "";
H2 Connection Parameters
AUTO_SERVER=TRUE: Allows multiple connections to the same database
DB_CLOSE_DELAY=-1: Keeps database open even when all connections close
file: prefix: Uses file-based storage instead of in-memory