チュートリアル
起動とH2コンソールの使用JDBCを使用してデータベースに接続
新しいデータベースを作成する
サーバーを使用する
Hibernateを使用する
Using TopLink and Glassfish
Webアプリケーションで データベースを使用する
CSV (Comma Separated Values) サポート
アップグレード、 バックアップ、修復
Command Line Tools
OpenOffice Baseを使用する
Java Web Start / JNLP
Using a Connection Pool
フルテキストサーチ
User-Defined Variables
Date and Time
起動とH2コンソールの使用
このアプリケーションはブラウザインターフェースを使ってSQLデータベースにアクセスします。 これは、H2データベース、またはJDBC APIをサポートする別のデータベースであるかもしれません。

これはクライアント / サーバーアプリケーションで、サーバーとクライアントの両方実行されることが必要です。
プラットフォームと環境によって、アプリケーションの起動方法が多数あります:
OS | 起動 |
---|---|
Windows |
[スタート]、 [すべてのプログラム]、 [H2]、 [H2 Console]をクリックします 正しく動作したら、 システムトレイにアイコンが追加されます: ![]() システムトレイアイコンが表示されなかったら、 Javaが正しくインストールされていないのかもしれません。 (この場合は、 他のアプリケーション起動方法を試して下さい) ブラウザウィンドウが開き、ログインページが表示されます。 (URL: http://localhost:8082/) |
Windows |
ファイルブラウザを開き、h2/binフォルダまで進み、h2.batをダブルクリックします。 正しく動作したら、システムトレイにアイコンが追加されます。 問題があれば、コンソールウィンドウにエラーメッセージが表示されます。 ブラウザウィンドウが開き、ログインページが表示されます。 (URL: http://localhost:8082/) |
Any |
コンソールウィンドウを開き、'h2/lib'ディレクトリまで進み、下記を実行します: java -cp h2.jar org.h2.tools.Server |
ファイアウォール
サーバーを起動させたら、ファイアウォールによるセキュリティ警告を受けるでしょう (1度インストールした場合)。外部ネットワークからあなたのマシンのデータベースにアクセスされたくないのであれば、ファイアーウォールが他の接続を遮断します。ローカルマシンからの接続はまだつながっています。他のコンピュータから、このコンピューターのデータベースにアクセスしたい場合のみ、 ファイアウォールでリモート接続を許可する必要があります。
小さなファイアーウォールはすでにサーバーに組み込まれています。 デフォルトによるこの構造は、他のコンピューターがサーバーにアクセスすることを許可していません。 これは、好きなように変更することができます (他のコンピューターからの接続を許可します)。
ネイティブ バージョン
ネイティブ バージョンはJavaを必要としていません。なぜなら、これはGCJを使用してコンパイルされるからです。しかし、H2は現在、Windows上のGCJプロジェクトでは実行されません。異なったプラットフォームでソフトウェアをコンパイルすることが可能です。
Javaをテストする
インストールしたJavaのバージョンを調べるためには、 コマンドプロンプトを開き、 下記を入力します:
java -version
もしエラーメッセージが表示されたら、Javaのバイナリディレクトリを環境変数のPathに追加します。
エラーメッセージ 'Port is in use'
ひとつのH2コンソールのみ起動することができます。 そうでなければ、次のようなエラーメッセージが表示されます:
Port is in use, maybe another ... server already running on...
複数のコンソールアプリケーションを同じコンピューターで起動することは可能です (異なったポートを使用します)、しかし、コンソールが複数の同時接続を維持するということは、普通は必要とされていません。
他のポートを使用する
もしポートが他のアプリケーションによって使用されている場合は、H2コンソールを異なったポートで起動したいはずです。これは、.h2.server.properties.ファイル内のポートを変更することにより実行できます。このファイルはユーザディレクトリ内に格納されています (Windowsでは通常、"Documents and Settings/<ユーザ名>")。関連する項目はwebPortです。
起動成功
コンソールウィンドウからのサーバー起動が成功したら、新しいウィンドウが開き、 下記のように表示されます:
H2 Server running on port 9092 Webserver running on https://localhost:8082/
ウィンドウ内をクリックしないで下さい; アプリケーションが遮断されてしまいます (Fast-Edit モードが有効の場合)。
ブラウザを使用してサーバーに接続
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.
複数の同時セッション
複数の同時ブラウザセッションがサポートされています。 データベースオブジェクトはサーバーに属しているため、同時接続の数はサーバーアプリケーションの利用可能メモリによって制限されています。
アプリケーションプロパティ
サーバーを起動するとローカルのホームディレクトリに .h2.server.properties と呼ばれるファイル構成が作成されます。Windowsのインストールでは、このファイルは will be in the directory C:\Documents and Settings\[ユーザ名]のディレクトリ内にあります。このファイルはアプリケーションのセッティングに含まれています。
ログイン
ログインページでは、データベースに接続するための接続情報を設定する必要があります。 JDBCドライバをデータベースのクラスに設定し、JDBCのURL、ユーザ名とパスワードを入力します。 完了したら [Connect] をクリックします。
保存された設定をあらかじめ保存し、再び使用することができます。設定はアプリケーションプロパティファイルに記憶されます。
エラーメッセージ
エラーメッセージは赤で表示されます。 メッセージをクリックすることによって、例外の記録の表示、非表示を切り替えることができます。
データベースドライバの追加
H2DRIVERSかCLASSPATHの環境変数に、ドライバのJarファイルの位置を追加することにより、データベースドライバの追加を行うことができます。 例 (Windowsの場合): データベースドライバのライブラリに C:\Programs\hsqldb\lib\hsqldb.jar を追加し、H2DRIVERSの環境変数に C:\Programs\hsqldb\lib\hsqldb.jar を設定します。
複数のドライバを設定することも可能です; それぞれのパスは ';' (Windows) や ':' (他のOS) で区切ります。 パス名内のスペースは有効です。設定は引用されません。
アプリケーションを使用する
アプリケーションは3つのメインパネルを保持しています。上部のツールバー、左側のツリーとクエリ、右側の結果表示パネルです。データベースオブジェクト (例; テーブル) は左側のパネルに一覧表示されます。クエリパネルにSQLコマンドを打ち、 'Run' をクリックします。 コマンドの結果は、コマンドのすぐ下に表示されます。
テーブル名、またはカラム名をインサートする
テーブル名やカラム名は、ツリー内のテーブル名、カラム名をクリックすることによってスクリプトにインサートすることができます。クエリが空の時にテーブルをクリックすると、 'SELECT * FROM ...' も同様に追加されます。 クエリを入力している間、使用されているテーブルはツリー内で自動的に拡張されます。例えば、 'SELECT * FROM TEST T WHERE T.' と入力すると、ツリー内のTESTテーブルは自動的に拡張されます。
切断とアプリケーションの終了
ブラウザでは、ツールバーパネルの 'Disconnect' をクリックします。データベースからログアウトします。しかし、サーバーはまだ接続されていて、 新しいセッションを受け入れる準備をしています。
サーバーを止めるためには、システムトレイアイコンを右クリックし、 [Exit] を選択します。もしアイコンが表示されていないのであれば、 (別の方法で実行した場合) サーバーが実行されたコンソール上で [Ctrl]+[C] を押すか (Windowsの場合)、コンソールウィンドウを閉じます。
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 } }
このコードは最初にドライバをロードして (Class.forName())、 接続を開始します (DriverManager.getConnection())。 このドライバの名前は全てのケースにおいて "org.h2.Driver" です。 データベースに認識されるため、データベースのURLは常に jdbc:h2: から始まります。 getConnection() 内の2番目のパラメーターはユーザ名を指しています ('sa' はこの場合、システム管理者を表しています)。3番目のパラメーターはパスワードです。このデータベースでは、ユーザ名は大文字と小文字を区別していませんが、パスワードは大文字と小文字を区別しています。
新しいデータベースを作成する
初期設定では、データベースの指定されたURLがまだ存在しない場合、自動的に新しい (空の) データベースが作られます。
サーバーを使用する
H2は現在、3つのサーバーをサポートしています: Webサーバー、TCPサーバー、ODBCサーバーです。 これらのサーバーは異なった方法で起動します。
コマンドラインから起動する
初期設定でコマンドラインからサーバーを起動させるには、次のように実行します。
java org.h2.tools.Server
サーバーはデフォルトオプションで起動します。オプションの一覧を取得するには、次のように実行します。
java org.h2.tools.Server -?
異なったポートの使用が可能なオプションや、サーバーの一部を起動、終了させるオプションなどがあります。 詳細はサーバーツールのAPIドキュメントをご覧下さい。
TCPサーバーに接続する
データベースへリモート接続するためには、TCPサーバーを使用します。次のドライバとデータベースURLを利用します:
- JDBCドライバクラス: org.h2.Driver
- データベースURL: jdbc:h2:tcp://localhost/~/test
データベースURLについての詳細は、特徴内のページをご覧下さい。
アプリケーション内で起動する
アプリケーション内からサーバーを起動、終了することも可能です。 以下はサンプルコードです:
import org.h2.tools.Server; ... // start the TCP Server Server server = Server.createTcpServer(args).start(); ... // stop the TCP Server server.stop();
他の過程からTCPサーバーを終了する
TCPサーバーは他の過程から終了することができます。 コマンドラインからサーバーを終了するには、次のように実行します:
java org.h2.tools.Server -tcpShutdown tcp://localhost:9092
ユーザアプリケーションからサーバーを終了するには、次のコードを使用します:
org.h2.tools.Server.shutdownTcpServer("tcp://localhost:9094");
この機能はサーバー上の System.exit を呼んでいます。この機能は、データベースが次回起動された時のリカバリーを回避するため、データベースへの全ての接続が切断された後に呼ばれます。リモートサーバーを終了するには、サーバー上でリモート接続が可能である必要があります。
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 TopLink and Glassfish
To use H2 with Glassfish (or Sun AS), set the Datasource Classname to org.h2.jdbcx.JdbcDataSource
. You can set this in the GUI at Application Server - Resources - JDBC - Connection Pools, or by editing the file sun-resources.xml
: at element jdbc-connection-pool
, set the attribute datasource-classname
to org.h2.jdbcx.JdbcDataSource
.
The H2 database is compatible with HSQLDB and PostgreSQL. To take advantage of H2 specific features, use the H2Platform
. The source code of this platform is included in H2 at src/tools/oracle/toplink/essentials/platform/database/DatabasePlatform.java.txt
. You will need to copy this file to your application, and rename it to .java. To enable it, change the following setting in persistence.xml:
<property name="toplink.target-database" value="oracle.toplink.essentials.platform.database.H2Platform"/>
In old versions of Glassfish, the property name is toplink.platform.class.name
.
Webアプリケーションで データベースを使用する
Webアプリケーション内からデータベースに接続するには様々な方法があります。 以下はTomcatかJBossを使用の場合のいくつかの例です。
エンベッドモード
(現在)最も簡単なソリューションはエンベッドモードでデータベースを使用することです。 それは、アプリケーションが起動する時や (良いソリューションは Servletリスナーを使用します。下記参照)、セッションが起動する時、アプリケーションにおける接続が開始するということを意味します。データベースは、セッションやアプリケーションが同じ過程で実行している限り、多様なセッションやアプリケーションから同時に接続されることが可能です。 多くのServletコンテナは (例; Tomcat) ただひとつのプロセスで利用されるので、問題はありません。 (Tomcatをクラスターモードで起動している場合を除いて)。 Tomcatはマルチスレッドとマルチクラスローダーを使用しています。もし複数のアプリケーションが同じデータベースに同時にアクセスする場合、データベースjarをshared/lib、またはserver/libディレクトリに置く必要があります。 webアプリケーションが起動した時にデータベースを開き、webアプリケーションが終了した時にデータベースを閉じるのが良い方法です。もし複数のアプリケーションを使用する場合、そのうちひとつのアプリケーションをこのように動作することが必要です。アプリケーションでは、セッションごとにひとつの接続を使うか、リクエスト(アクション)ごとにひとつの接続を使うという概念があります。これらの接続はできる限り、使用後に終了させます(しかし、終了させなくても悪くはありません)。
サーバーモード
サーバーモードは類似していますが、他のプロセスでサーバーを起動させることを許可しています。
データベースの起動と終了にServletリスナーを使用する
以下を web.xmlファイルに追記して下さい。 (context-paramとfilterの間):
<listener> <listener-class>org.h2.server.web.DbStarter</listener-class> </listener>
データベースへのアクセス方法についての詳細は、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) サポート
データベースにCSVREADとCSVWRITEの関数を使用することで、 CSVファイルサポートを使用することができ、スタンドアロンツールとしてデータベースの外でCSVライブラリを使用することができます。
データベース内からCSVファイルに書き込む
クエリからCSVファイルを作成するのに、組込み関数 CSVWRITEを使用することができます。例:
CREATE TABLE TEST(ID INT, NAME VARCHAR); INSERT INTO TEST VALUES(1, 'Hello'), (2, 'World'); CALL CSVWRITE('test.csv', 'SELECT * FROM TEST');
データベース内からCSVファイルを読み込む
CSVREAD関数を使用してCSVファイルを読み込むことができます。 例:
SELECT * FROM CSVREAD('test.csv');
JavaアプリケーションからCSVファイルに書き込む
データベースを全く使用しなくても、JavaアプリケーションでCSVツールを使用することができます。 例:
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);
JavaアプリケーションからCSVファイルを読み込む
データベースを開かなくてもCSVファイルを読み込むことができます。 例:
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();
アップグレード、 バックアップ、修復
データベースのアップグレー
あるバージョンのデータベースエンジンを次のバージョンにアップグレードする際の推奨する方法は、 古いエンジンを使って(SQLスクリプトのフォームでの)データベースのバックアップを作成し、新しいエンジンを使ってSQLスクリプトを実行します。
バックアップ
異なった方法のデータベースのバックアップがあります。例えば、データベースファイルをコピーすることが可能です。しかしながら、この方法はデータベースが使用されている間は推奨しません。データベースは人が判読しやすく、極めて大きいというわけではありません。データベースバックアップの推奨する方法は、圧縮したSQLスクリプトを作成することです。この方法は、バックアップツールを使用することで可能です:
java org.h2.tools.Script -url jdbc:h2:~/test -user sa -script test.zip -options compression zip
オプションについての情報は、SQLコマンドスクリプトをご覧下さい。バックアップは遠隔で行えますが、ファイルはサーバー側に作られます。サーバーからファイルを取るのに、ビルトインFTPサーバーを使用することができます。データベースのバックアップを作るのに、SQLコマンドスクリプトを 使用することもできます。
修復
SQLスクリプトファイルからデータベースを修復するには、RunScriptツールを使用する必要があります:
java org.h2.tools.RunScript -url jdbc:h2:~/test -user sa -script test.zip -options compression zip
オプションについての情報は、SQLコマンド RUNSCRIPTをご覧下さい。修復は遠隔で行えますが、サーバー側にファイルが存在する必要があります。サーバーからファイルをコピーするのに、ビルトインFTPサーバーを使用することができます。SQLスクリプトを実行するために、 SQLコマンド RUNSCRIPTを使用することができます。SQLスクリプトファイルには、RUNSCRIPTコマンドのフォーム内に他のスクリプトファイルのリファレンスが含まれています。しかしながら、サーバーモードを使用している時、リファレンススクリプトファイルはサーバー側で利用可能であることが必要です。
オンラインバックアップ
BACKUP SQLステートメントとバックアップツールの両方が全てのデータベースファイルをzipファイル形式で作成します。しかし、このファイルのコンテンツは人間が解読可能なものではありません。SCRIPTステートメントを除いて、BACKUPステートメントはデータベースオブジェクトをロックしないため、他のユーザーをブロックしません。結果として、バックアップは一貫性のあるトランザクションです:
BACKUP TO 'backup.zip'
バックアップツール (org.h2.tools.Backup) はオンラインバックアップを作成するために利用されません; このプログラムが実行されている間、データベースは使用されてはいけません。
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:
- バックアップ 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.
OpenOffice Baseを使用する
OpenOffice.org Base はJDBC API上のデータベースアクセスをサポートしています。 OpenOffice Baseを使ってH2データベースに接続するためには、最初にOpenOfficeにJDBCドライバを追加する必要があります。H2データベースに接続する手順:
- 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)
- OpenOffice Base を起動する
- 存在するデータベースに接続し、JDBCを選択し、[Next] をクリックする
- Example datasource URL: jdbc:h2:~/test
- JDBCドライバクラス: 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
Java Web Start / JNLP (Java Network Launch Protocol) を使用している時、パーミッションタグは.jnlp ファイルに設定され、application.jarファイルは署名されていなければなりません。そうでなければ、ファイルシステムに書き込もうとした時、次の例外が発生するでしょう: java.security.AccessControlException: access denied (java.io.FilePermission ... read) パーミッションタグの例:
<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();
フルテキストサーチ
H2はLuceneフルテキストサーチとnativeフルテキストサーチの実装をサポートしています。
Nativeフルテキストサーチを使用する
初期化するには、次を呼び出します:
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はスキーマ、TESTはテーブル名です。カラム名のリスト (分離されたカラム) はオプションです。このケースでは、全てのカラムがインデックスです。インデックスはリードタイムに更新されます。インデックスを検索するには、次のクエリーを使用します:
SELECT * FROM FT_SEARCH('Hello', 0, 0);
Javaアプリケーション内からインデックスを呼び出すことも可能です:
org.h2.fulltext.FullText.search(conn, text, limit, offset)
Luceneフルテキストサーチを使用する
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はスキーマ、TESTはテーブル名です。カラム名のリスト (分離されたカラム) はオプションです。このケースでは、全てのカラムがインデックスです。インデックスはリードタイムに更新されます。インデックスを検索するには、次のクエリーを使用します:
SELECT * FROM FTL_SEARCH('Hello', 0, 0);
Javaアプリケーション内からインデックスを呼び出すことも可能です:
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.