# Tutorial Starting and Using the H2 Console Connecting to a Database using JDBC Creating New Databases Using the Server Using Hibernate Using Databases in Web Applications CSV (Comma Separated Values) Support Upgrade, Backup, and Restore Command Line Tools Using OpenOffice Base Java Web Start / JNLP Using a Connection Pool Fulltext Search User-Defined Variables Date and Time ## Starting and Using the H2 Console This application lets you access a SQL database using a browser interface. This can be a H2 database, or another database that supports the JDBC API. This is a client / server application, so both a server and a client (a browser) are required to run it. Depending on your platform and environment, there are multiple ways to start the application:
OS | Start
--- | ---
Windows | Click [Start], [All Programs], [H2], and [H2 Console (Command Line)] When using the Sun JDK 1.4 or 1.5, a window with the title 'H2 Console ' should appear. When using the Sun JDK 1.6, an icon will be added to the system tray: If you don't get the window and the system tray icon, then maybe Java is not installed correctly (in this case, try another way to start the application). A browser window should open and point to the Login page http://localhost:8082).
Windows | Open a file browser, navigate to h2/bin, and double click on h2.bat. A console window appears. If there is a problem, you will see an error message in this window. A browser window will open and point to the Login page (URL: http://localhost:8082).
Any | Open a console window, navigate to the directory 'h2/bin' and type:
    java -cp h2.jar org.h2.tools.Server
### Firewall If you start the server, you may get a security warning from the firewall (if you have installed one). If you don't want other computers in the network to access the application on your machine, you can let the firewall block those connections. The connection from the local machine will still work. Only if you want other computers to access the database on this computer, you need allow remote connections in the firewall. A small firewall is already built into the server: other computers may not connect to the server by default. To change this, go to 'Preferences' and select 'Allow connections from other computers'. ### Native Version The native version does not require Java, because it is compiled using GCJ. However H2 does currently not run stable with GCJ on Windows It is possible to compile the software to different platforms. ### Testing Java To check the Java version you have installed, open a command prompt and type:
    java -version
If you get an error message, you may need to add the Java binary directory to the path environment variable. ### Error Message 'Port is in use' You can only start one instance of the H2 Console, otherwise you will get the following error message: `Port is in use, maybe another ... server already running on...`. It is possible to start multiple console applications on the same computer (using different ports), but this is usually not required as the console supports multiple concurrent connections. ### Using another Port If the port is in use by another application, you may want to start the H2 Console on a different port. This can be done by changing the port in the file .h2.server.properties. This file is stored in the user directory (for Windows, this is usually in "Documents and Settings/<username>"). The relevant entry is webPort. ### Starting Successfully If starting the server from a console window was successful, a new window will open and display the following text:
    H2 Server running on port 9092
    Webserver running on https://localhost:8082/
Don't click inside this window; otherwise you might block the application (if you have the Fast-Edit mode enabled). ### Connecting to the Server using a Browser If the server started successfully, you can connect to it using a web browser. The browser needs to support JavaScript, frames and cascading stylesheets (css). If you started the server on the same computer as the browser, go to http://localhost:8082 in the browser. If you want to connect to the application from another computer, you need to provide the IP address of the server, for example: http://192.168.0.2:8082. If you enabled SSL on the server side, the URL needs to start with HTTPS. ### Multiple Concurrent Sessions Multiple concurrent browser sessions are supported. As that the database objects reside on the server, the amount of concurrent work is limited by the memory available to the server application. ### Application Properties Starting the server will create a configuration file in you local home directory called `.h2.server.properties`. For Windows installations, this file will be in the directory `C:\Documents and Settings\[username]`. This file contains the settings of the application. ### Login At the login page, you need to provide connection information to connect to a database. Set the JDBC driver class of your database, the JDBC URL, user name and password. If you are done, click [Connect]. You can save and reuse previously saved settings. The settings are stored in the Application Properties file. ### Error Messages Error messages in are shown in red. You can show/hide the stack trace of the exception by clicking on the message. ### Adding Database Drivers Additional database drivers can be registered by adding the Jar file location of the driver to the environment variables H2DRIVERS or CLASSPATH. Example (Windows): To add the database driver library C:\Programs\hsqldb\lib\hsqldb.jar, set the environment variable H2DRIVERS to C:\Programs\hsqldb\lib\hsqldb.jar. Multiple drivers can be set; each entry needs to be separated with a ';' (Windows) or ':' (other operating systems). Spaces in the path names are supported. The settings must not be quoted. ### Using the Application The application has three main panels, the toolbar on top, the tree on the left and the query / result panel on the right. The database objects (for example, tables) are listed on the left panel. Type in a SQL command on the query panel and click 'Run'. The result of the command appears just below the command. ### Inserting Table Names or Column Names The table name and column names can be inserted in the script by clicking them in the tree. If you click on a table while the query is empty, a 'SELECT * FROM ...' is added as well. While typing a query, the table that was used is automatically expanded in the tree. For, example if you type 'SELECT * FROM TEST T WHERE T.' then the table TEST is automatically expanded in the tree. ### Disconnecting and Stopping the Application On the browser, click 'Disconnect' on the toolbar panel. You will be logged out of the database. However, the server is still running and ready to accept new sessions. To stop the server, right click on the system tray icon and select [Exit]. If you don't have the icon (because you started it in another way), press [Ctrl]+[C] on the console where the server was started (Windows), or close the console window. ## Connecting to a Database using JDBC To connect to a database, a Java application first needs to load the database driver, and then get a connection. A simple way to do that is using the following code:
    import java.sql.*;
    public class Test {
      public static void main(String[] a)
      throws Exception {
        Class.forName("org.h2.Driver");
        Connection conn = DriverManager.
          getConnection("jdbc:h2:~/test", "sa", "");
        // add application code here
      }
    }
This code first loads the driver (`Class.forName()`) and then opens a connection (using `DriverManager.getConnection()`). The driver name is `"org.h2.Driver"` in every case. The database URL always needs to start with `jdbc:h2:` to be recognized by this database. The second parameter in the `getConnection()` call is the user name ('sa' for System Administrator in this example). The third parameter is the password. Please note that in this database, user names are not case sensitive, but passwords are case sensitive. ## Creating New Databases By default, if the database specified in the URL does not yet exist, a new (empty) database is created automatically. The user that created the database automatically becomes the administrator of this database. ## Using the Server H2 currently supports three servers: a Web Server, a TCP Server and an ODBC Server. The servers can be started in different ways. ### Starting the Server from Command Line To start the Server from the command line with the default settings, run
    java org.h2.tools.Server
This will start the Server with the default options. To get the list of options and default values, run
    java org.h2.tools.Server -?
There are options available to use different ports, and start or not start parts of the Server and so on. For details, see the API documentation of the Server tool. ### Connecting to the TCP Server To remotely connect to a database using the TCP server, use the following driver and database URL: JDBC driver class: org.h2.Driver Database URL: jdbc:h2:tcp://localhost/~/test For details about the database URL, see also in Features. ### Starting the Server within an Application It is also possible to start and stop a Server from within an application. Sample code:
    import org.h2.tools.Server;
    ...
    // start the TCP Server
    Server server = Server.createTcpServer(args).start();
    ...
    // stop the TCP Server
    server.stop();
### Stopping a TCP Server from Another Process The TCP Server can be stopped from another process. To stop the server from the command line, run:
    java org.h2.tools.Server -tcpShutdown tcp://localhost:9092
To stop the server from a user application, use the following code:
    org.h2.tools.Server.shutdownTcpServer("tcp://localhost:9094");
This function will call System.exit on the server. This function should be called after all connections to the databases are closed to avoid recovery when the databases are opened the next time. To stop remote server, remote connections must be enabled on the server. ## Using Hibernate This database supports Hibernate version 3.1 and newer. You can use the HSQLDB Dialect, or the native H2 Dialect. Unfortunately the H2 Dialect included in Hibernate is buggy. A patch for Hibernate has been submitted. The dialect for the newest version of Hibernate is also available at src/tools/org/hibernate/dialect/H2Dialect.java.txt. You can rename it to H2Dialect.java and include this as a patch in your application. ## Using Databases in Web Applications There are multiple ways to access a database from within web applications. Here are some examples if you use Tomcat or JBoss. ### Embedded Mode The (currently) simplest solution is to use the database in the embedded mode, that means open a connection in your application when it starts (a good solution is using a Servlet Listener, see below), or when a session starts. A database can be accessed from multiple sessions and applications at the same time, as long as they run in the same process. Most Servlet Containers (for example Tomcat) are just using one process, so this is not a problem (unless you run Tomcat in clustered mode). Tomcat uses multiple threads and multiple classloaders. If multiple applications access the same database at the same time, you need to put the database jar in the shared/lib or server/lib directory. It is a good idea to open the database when the web application starts, and close it when the web application stops. If using multiple applications, only one (any) of them needs to do that. In the application, an idea is to use one connection per Session, or even one connection per request (action). Those connections should be closed after use if possible (but it's not that bad if they don't get closed). ### Server Mode The server mode is similar, but it allows you to run the server in another process. ### Using a Servlet Listener to Start and Stop a Database Add the h2.jar file your web application, and add the following snippet to your web.xml file (after context-param and before filter):
    <listener>
       <listener-class>org.h2.server.web.DbStarter</listener-class>
    </listener>
For details on how to access the database, see the code DbStarter.java By default the DbStarter listener opens an embedded connection using the database URL jdbc:h2:~/test and user name and password 'sa'. It can also start the TCP server, however this is disabled by default. To enable it, use the db.tcpServer parameter in web.xml. Here is the complete list of options. These options are set just after the display-name and description tag, but before any listener and filter tags:
    <context-param>
       <param-name>db.url</param-name>
       <param-value>jdbc:h2:~/test</param-value>
    </context-param>
    <context-param>
       <param-name>db.user</param-name>
       <param-value>sa</param-value>
    </context-param>
    <context-param>
       <param-name>db.password</param-name>
       <param-value>sa</param-value>
    </context-param>
    <context-param>
       <param-name>db.tcpServer</param-name>
       <param-value>-tcpAllowOthers</param-value>
    </context-param>
When the web application is stopped, the database connection will be closed automatically. If the server is started within the DbStarter, it will also be stopped automatically when the web application is stopped. ## CSV (Comma Separated Values) Support The CSV file support can be used inside the database using the functions CSVREAD and CSVWRITE, and the CSV library can be used outside the database as a standalone tool. ### Writing a CSV File from Within a Database The built-in function CSVWRITE can be used to create a CSV file from a query. Example:
    CREATE TABLE TEST(ID INT, NAME VARCHAR);
    INSERT INTO TEST VALUES(1, 'Hello'), (2, 'World');
    CALL CSVWRITE('test.csv', 'SELECT * FROM TEST');
### Reading a CSV File from Within a Database A CSV file can be read using the function CSVREAD. Example:
    SELECT * FROM CSVREAD('test.csv');
### Writing a CSV File from a Java Application The CSV tool can be used in a Java application even when not using a database at all. Example:
    import org.h2.tools.Csv;
    import org.h2.tools.SimpleResultSet;
    ...
    SimpleResultSet rs = new SimpleResultSet();
    rs.addColumn("NAME", Types.VARCHAR, 255, 0);
    rs.addColumn("EMAIL", Types.VARCHAR, 255, 0);
    rs.addColumn("PHONE", Types.VARCHAR, 255, 0);
    rs.addRow(new String[] { "Bob Meier", "bob.meier@abcde.abc", "+41123456789" });
    rs.addRow(new String[] { "John Jones", "john.jones@abcde.abc", "+41976543210" });
    Csv.getInstance().write("data/test.csv", rs, null);
### Reading a CSV File from a Java Application It is possible to read a CSV file without opening a database. Example:
    import org.h2.tools.Csv;
    ...
    ResultSet rs = Csv.getInstance().read("data/test.csv", null, null);
    ResultSetMetaData meta = rs.getMetaData();
    while (rs.next()) {
        for (int i = 0; i < meta.getColumnCount(); i++) {
            System.out.println(meta.getColumnLabel(i + 1) + ": " + rs.getString(i + 1));
        }
        System.out.println();
    }
    rs.close();
## Upgrade, Backup, and Restore ### Database Upgrade The recommended way to upgrade from one version of the database engine to the next version is to create a backup of the database (in the form of a SQL script) using the old engine, and then execute the SQL script using the new engine. ### Backup using the Script Tool There are different ways to backup a database. For example, it is possible to copy the database files. However, this is not recommended while the database is in use. Also, the database files are not human readable and quite large. The recommended way to backup a database is to create a compressed SQL script file. This can be done using the Script tool:
    java org.h2.tools.Script -url jdbc:h2:~/test -user sa -script test.zip -options compression zip
It is also possible to use the SQL command SCRIPT to create the backup of the database. For more information about the options, see the SQL command SCRIPT. The backup can be done remotely, however the file will be created on the server side. The built in FTP server could be used to retrieve the file from the server. ### Restore from a Script To restore a database from a SQL script file, you can use the RunScript tool:
    java org.h2.tools.RunScript -url jdbc:h2:~/test -user sa -script test.zip -options compression zip
For more information about the options, see the SQL command RUNSCRIPT. The restore can be done remotely, however the file needs to be on the server side. The built in FTP server could be used to copy the file to the server. It is also possible to use the SQL command RUNSCRIPT to execute a SQL script. SQL script files may contain references to other script files, in the form of RUNSCRIPT commands. However, when using the server mode, the references script files need to be available on the server side. ### Online Backup The BACKUP SQL statement and the Backup tool both create a zip file with all database files. However, the contents of this file are not human readable. Other than the SCRIPT statement, the BACKUP statement does not lock the database objects, and therefore does not block other users. The resulting backup is transactionally consistent:
    BACKUP TO 'backup.zip'
The Backup tool (org.h2.tools.Backup) can not be used to create a online backup; the database must not be in use while running this program. ## Command Line Tools This database comes with a number of command line tools. To get more information about a tool, start it with the parameter '-?', for example:
    java -cp h2.jar org.h2.tools.Backup -?
The command line tools are: Backup creates a backup of a database. ChangeFileEncryption allows changing the file encryption password or algorithm of a database. Console starts the browser based H2 Console. ConvertTraceFile converts a .trace.db file to a Java application and SQL script. CreateCluster creates a cluster from a standalone database. DeleteDbFiles deletes all files belonging to a database. Script allows converting a database to a SQL script for backup or migration. Recover helps recovering a corrupted database. Restore restores a backup of a database. RunScript runs a SQL script against a database. Server is used in the server mode to start a H2 server. Shell is a command line database tool. The tools can also be called from an application by calling the main or another public methods. For details, see the Javadoc documentation. ## Using OpenOffice Base OpenOffice.org Base supports database access over the JDBC API. To connect to a H2 database using OpenOffice Base, you first need to add the JDBC driver to OpenOffice. The steps to connect to a H2 database are: Start OpenOffice Writer, go to [Tools], [Options] Make sure you have selected a Java runtime environment in OpenOffice.org / Java Click [Class Path...], [Add Archive...] Select your h2.jar (location is up to you, could be wherever you choose) Click [OK] (as much as needed), stop OpenOffice (including the Quickstarter) Start OpenOffice Base Connect to an existing database; select JDBC; [Next] Example datasource URL: jdbc:h2:~/test JDBC driver class: org.h2.Driver Now you can access the database stored in the current users home directory. To use H2 in NeoOffice (OpenOffice without X11): In NeoOffice, go to [NeoOffice], [Preferences] Look for the page under [NeoOffice], [Java] Click [Classpath], [Add Archive...] Select your h2.jar (location is up to you, could be wherever you choose) Click [OK] (as much as needed), restart NeoOffice. Now, when creating a new database using the "Database Wizard": Select "connect to existing database" and the type "jdbc". Click next. Enter your h2 database URL. The normal behavior of H2 is that a new db is created if it doesn't exist. Next step - up to you... you can just click finish and start working. Another solution to use H2 in NeoOffice is: Package the h2 jar within an extension package Install it as a Java extension in NeoOffice This can be done by create it using the NetBeans OpenOffice plugin. See also Extensions Development. ## Java Web Start / JNLP When using Java Web Start / JNLP (Java Network Launch Protocol), permissions tags must be set in the .jnlp file, and the application .jar file must be signed. Otherwise, when trying to write to the file system, the following exception will occur: java.security.AccessControlException: access denied (java.io.FilePermission ... read). Example permission tags:
    <security>
        <all-permissions/>
    </security>
## Using a Connection Pool For many databases, opening a connection is slow, and it is a good idea to use a connection pool to re-use connections. For H2 however opening a connection usually is fast if the database is already open. Using a connection pool for H2 actually slows down the process a bit, except if file encryption is used (in this case opening a connection is about half as fast as using a connection pool). A simple connection pool is included in H2. It is based on the Mini Connection Pool Manager from Christian d'Heureuse. There are other, more complex connection pools available, for example DBCP. The build-in connection pool is used as follows:
    // init
    import org.h2.jdbcx.*;
    ...
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:~/test");
    ds.setUser("sa");
    ds.setPassword("sa");
    JdbcConnectionPool cp = JdbcConnectionPool.create(ds);

    // use
    Connection conn = cp.getConnection();
    ...
    conn.close();

    // dispose
    cp.dispose();
## Fulltext Search H2 supports Lucene full text search and native full text search implementation. ### Using the Native Full Text Search To initialize, call:
    CREATE ALIAS IF NOT EXISTS FT_INIT FOR "org.h2.fulltext.FullText.init";
    CALL FT_INIT();
You need to initialize it in each database where you want to use it. Afterwards, you can create a full text index for a table using:
    CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR);
    INSERT INTO TEST VALUES(1, 'Hello World');
    CALL FT_CREATE_INDEX('PUBLIC', 'TEST', NULL);
PUBLIC is the schema, TEST is the table name. The list of column names (column separated) is optional, in this case all columns are indexed. The index is updated in read time. To search the index, use the following query:
    SELECT * FROM FT_SEARCH('Hello', 0, 0);
You can also call the index from within a Java application:
    org.h2.fulltext.FullText.search(conn, text, limit, offset)
### Using the Lucene Fulltext Search To use the Lucene full text search, you need the Lucene library in the classpath. How his is done depends on the application; if you use the H2 Console, you can add the Lucene jar file to the environment variables H2DRIVERS or CLASSPATH. To initialize the Lucene full text search in a database, call:
    CREATE ALIAS IF NOT EXISTS FTL_INIT FOR "org.h2.fulltext.FullTextLucene.init";
    CALL FTL_INIT();
You need to initialize it in each database where you want to use it. Afterwards, you can create a full text index for a table using:
    CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR);
    INSERT INTO TEST VALUES(1, 'Hello World');
    CALL FTL_CREATE_INDEX('PUBLIC', 'TEST', NULL);
PUBLIC is the schema, TEST is the table name. The list of column names (column separated) is optional, in this case all columns are indexed. The index is updated in read time. To search the index, use the following query:
    SELECT * FROM FTL_SEARCH('Hello', 0, 0);
You can also call the index from within a Java application:
    org.h2.fulltext.FullTextLucene.search(conn, text, limit, offset)
## User-Defined Variables This database supports user-defined variables. Variables start with @ and can be used wherever expressions or parameters are used. Variables not persisted and session scoped, that means only visible for the session where they are defined. A value is usually assigned using the SET command:
    SET @USER = 'Joe';
It is also possible to change a value using the SET() method. This is useful in queries:
    SET @TOTAL = NULL;
    SELECT X, SET(@TOTAL, IFNULL(@TOTAL, 1.) * X) F FROM SYSTEM_RANGE(1, 50);
Variables that are not set evaluate to NULL. The data type of a user-defined variable is the data type of the value assigned to it, that means it is not necessary (or possible) to declare variable names before using them. There are no restrictions on the assigned values; large objects (LOBs) are supported as well. ## Date and Time Date, time and timestamp values support ISO 8601 formatting, including time zone:
    CALL TIMESTAMP '2008-01-01 12:00:00+01:00';
If the time zone is not set, the value is parsed using the current time zone setting of the system. Date and time information is stored in H2 database files in GMT (Greenwich Mean Time). If the database is opened using another system time zone, the date and time will change accordingly. If you want to move a database from one time zone to the other and don't want this to happen, you need to create a SQL script file using the SCRIPT command or Script tool, and then load the database using the RUNSCRIPT command or the RunScript tool in the new time zone.