tutorial.html 54.1 KB
Newer Older
1 2
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
3 4
Copyright 2004-2019 H2 Group. Multiple-Licensed under the MPL 2.0,
and the EPL 1.0 (http://h2database.com/html/license.html).
5 6 7
Initial Developer: H2 Group
-->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
8 9
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
Thomas Mueller's avatar
Thomas Mueller committed
10
<meta name="viewport" content="width=device-width, initial-scale=1" />
11
<title>
12
Tutorial
13 14
</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
15 16 17 18 19 20
<!-- [search] { -->
<script type="text/javascript" src="navigation.js"></script>
</head><body onload="frameMe();">
<table class="content"><tr class="content"><td class="content"><div class="contentDiv">
<!-- } -->

21
<h1 id="tutorial_index">Tutorial</h1>
22 23
<a href="#tutorial_starting_h2_console">
    Starting and Using the H2 Console</a><br />
24 25
<a href="#console_syntax">
    Special H2 Console Syntax</a><br />
26 27 28 29 30 31 32 33 34 35 36 37
<a href="#console_settings">
    Settings of the H2 Console</a><br />
<a href="#connecting_using_jdbc">
    Connecting to a Database using JDBC</a><br />
<a href="#creating_new_databases">
    Creating New Databases</a><br />
<a href="#using_server">
    Using the Server</a><br />
<a href="#using_hibernate">
    Using Hibernate</a><br />
<a href="#using_toplink">
    Using TopLink and Glassfish</a><br />
38 39
<a href="#using_eclipselink">
    Using EclipseLink</a><br />
Thomas Mueller's avatar
Thomas Mueller committed
40 41
<a href="#using_activemq">
    Using Apache ActiveMQ</a><br />
Thomas Mueller's avatar
Thomas Mueller committed
42 43
<a href="#using_netbeans">
    Using H2 within NetBeans</a><br />
44 45
<a href="#using_jooq">
    Using H2 with jOOQ</a><br />
46 47
<a href="#web_applications">
    Using Databases in Web Applications</a><br />
Thomas Mueller's avatar
Thomas Mueller committed
48 49
<a href="#android">
    Android</a><br />
50 51 52 53 54 55
<a href="#csv">
    CSV (Comma Separated Values) Support</a><br />
<a href="#upgrade_backup_restore">
    Upgrade, Backup, and Restore</a><br />
<a href="#command_line_tools">
    Command Line Tools</a><br />
56
<a href="#shell_tool">
57
    The Shell Tool</a><br />
58 59 60 61 62 63 64 65 66 67 68 69 70 71
<a href="#open_office">
    Using OpenOffice Base</a><br />
<a href="#web_start">
    Java Web Start / JNLP</a><br />
<a href="#connection_pool">
    Using a Connection Pool</a><br />
<a href="#fulltext">
    Fulltext Search</a><br />
<a href="#user_defined_variables">
    User-Defined Variables</a><br />
<a href="#date_time">
    Date and Time</a><br />
<a href="#spring">
    Using Spring</a><br />
72 73
<a href="#osgi">
    OSGi</a><br />
Thomas Mueller's avatar
Thomas Mueller committed
74 75
<a href="#jmx">
    Java Management Extension (JMX)</a><br />
76

Thomas Mueller's avatar
Thomas Mueller committed
77
<h2 id="tutorial_starting_h2_console">Starting and Using the H2 Console</h2>
78
<p>
Thomas Mueller's avatar
Thomas Mueller committed
79
The H2 Console application lets you access a database using a browser.
80 81
This can be a H2 database, or another database that supports the JDBC API.
</p>
82 83 84
<img src="images/console-2.png"
    width="535" height="179"
    alt="Web Browser - H2 Console Server - H2 Database" />
85
<p>
Thomas Mueller's avatar
Thomas Mueller committed
86
This is a client/server application, so both a server and a client (a browser) are required to run it.
87
</p><p>
Thomas Mueller's avatar
Thomas Mueller committed
88
Depending on your platform and environment, there are multiple ways to start the H2 Console:
89
</p>
90
<table class="main">
91
<tr><th>OS</th><th>Start</th></tr>
92
<tr>
Thomas Mueller's avatar
Thomas Mueller committed
93 94
    <td>Windows</td>
    <td>
95
    Click [Start], [All Programs], [H2], and [H2 Console (Command Line)]<br />
96
    An icon will be added to the system tray:
97 98 99
    <img src="images/db-64-t.png"
        width="32" height="32"
        alt="H2 database icon" /><br />
100 101
    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).
Thomas Mueller's avatar
Thomas Mueller committed
102
    A browser window should open and point to the login page at <code>http://localhost:8082</code>.
Thomas Mueller's avatar
Thomas Mueller committed
103
    </td>
104 105
</tr>
<tr>
Thomas Mueller's avatar
Thomas Mueller committed
106 107
    <td>Windows</td>
    <td>
108 109
    Open a file browser, navigate to <code>h2/bin</code>, and
    double click on <code>h2.bat</code>.<br />
110
    A console window appears. If there is a problem, you will see an error message
Thomas Mueller's avatar
Thomas Mueller committed
111
    in this window. A browser window will open and point to the login page
112
    (URL: <code>http://localhost:8082</code>).
Thomas Mueller's avatar
Thomas Mueller committed
113
    </td>
114
</tr>
115 116 117
<tr>
    <td>Any</td>
    <td>
118
    Double click on the <code>h2*.jar</code> file.
Thomas Mueller's avatar
Thomas Mueller committed
119
    This only works if the <code>.jar</code> suffix is associated with Java.
120 121
    </td>
</tr>
122
<tr>
Thomas Mueller's avatar
Thomas Mueller committed
123 124
    <td>Any</td>
    <td>
Thomas Mueller's avatar
Thomas Mueller committed
125 126
    Open a console window, navigate to the directory <code>h2/bin</code>, and type:
    <pre>java -jar h2*.jar</pre>
Thomas Mueller's avatar
Thomas Mueller committed
127
    </td>
128 129 130 131 132 133 134 135 136 137 138 139 140
</tr>
</table>

<h3>Firewall</h3>
<p>
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.
</p>
<p>
It has been reported that when using Kaspersky 7.0 with firewall, the H2 Console is very slow when
Thomas Mueller's avatar
Thomas Mueller committed
141
connecting over the IP address. A workaround is to connect using 'localhost'.
142 143 144 145 146 147 148 149
</p>
<p>
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'.
</p>

<h3>Testing Java</h3>
<p>
150
To find out which version of Java is installed, open a command prompt and type:
151
</p>
152
<pre>
153 154 155 156 157 158
java -version
</pre>
<p>
If you get an error message, you may need to add the Java binary directory to the path environment variable.
</p>

159
<h3>Error Message 'Port may be in use'</h3>
160 161 162
<p>
You can only start one instance of the H2 Console,
otherwise you will get the following error message:
163
"The Web server could not be started. Possible cause: another server is already running...".
164 165 166 167 168 169
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.
</p>

<h3>Using another Port</h3>
<p>
Thomas Mueller's avatar
Thomas Mueller committed
170 171 172 173
If the default port of the H2 Console is already in use by another application,
then a different port needs to be configured. The settings are stored in a properties file.
For details, see <a href="#console_settings">Settings of the H2 Console</a>.
The relevant entry is <code>webPort</code>.
174
</p>
Thomas Mueller's avatar
Thomas Mueller committed
175
<p>
Thomas Mueller's avatar
Thomas Mueller committed
176
If no port is specified for the TCP and PG servers, each service will try to listen on its default port.
Thomas Mueller's avatar
Thomas Mueller committed
177 178
If the default port is already in use, a random port is used.
</p>
179 180 181 182

<h3>Connecting to the Server using a Browser</h3>
<p>
If the server started successfully, you can connect to it using a web browser.
Thomas Mueller's avatar
Thomas Mueller committed
183
Javascript needs to be enabled.
184
If you started the server on the same computer as the browser, open the URL <code>http://localhost:8082</code>.
185
If you want to connect to the application from another computer, you need to provide the IP address of the server, for example:
186
<code>http://192.168.0.2:8082</code>.
187
If you enabled TLS on the server side, the URL needs to start with <code>https://</code>.
188 189 190 191 192 193 194 195 196 197 198
</p>

<h3>Multiple Concurrent Sessions</h3>
<p>
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.
</p>

<h3>Login</h3>
<p>
At the login page, you need to provide connection information to connect to a database.
Thomas Mueller's avatar
Thomas Mueller committed
199
Set the JDBC driver class of your database, the JDBC URL, user name, and password.
200 201
If you are done, click [Connect].
</p><p>
202 203
You can save and reuse previously saved settings. The settings are stored in a properties file
(see <a href="#console_settings">Settings of the H2 Console</a>).
204 205 206 207 208 209 210 211 212 213
</p>

<h3>Error Messages</h3>
<p>
Error messages in are shown in red. You can show/hide the stack trace of the exception
by clicking on the message.
</p>

<h3>Adding Database Drivers</h3>
<p>
Thomas Mueller's avatar
Thomas Mueller committed
214 215 216
To register additional JDBC drivers (MySQL, PostgreSQL, HSQLDB,...),
add the jar file names to the environment variables <code>H2DRIVERS</code> or <code>CLASSPATH</code>.
Example (Windows): to add the HSQLDB JDBC driver
217 218 219
<code>C:\Programs\hsqldb\lib\hsqldb.jar</code>, set the environment variable
<code>H2DRIVERS</code> to
<code>C:\Programs\hsqldb\lib\hsqldb.jar</code>.
220
</p><p>
Thomas Mueller's avatar
Thomas Mueller committed
221
Multiple drivers can be set; entries need to be separated by <code>;</code> (Windows)
222
or <code>:</code> (other operating systems).
223 224 225
Spaces in the path names are supported. The settings must not be quoted.
</p>

226
<h3>Using the H2 Console</h3>
227
<p>
Thomas Mueller's avatar
Thomas Mueller committed
228 229 230
The H2 Console 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.
Type a SQL command in the query panel and click [Run]. The result appears just below the command.
231 232 233 234
</p>

<h3>Inserting Table Names or Column Names</h3>
<p>
Thomas Mueller's avatar
Thomas Mueller committed
235 236 237 238
To insert table and column names into the script, click on the item in the tree.
If you click on a table while the query is empty, then <code>SELECT * FROM ...</code> is added.
While typing a query, the table that was used is expanded in the tree.
For example if you type <code>SELECT * FROM TEST T WHERE T.</code> then the table TEST is expanded.
239 240 241 242
</p>

<h3>Disconnecting and Stopping the Application</h3>
<p>
Thomas Mueller's avatar
Thomas Mueller committed
243
To log out of the database, click [Disconnect] in the toolbar panel.
244 245 246
However, the server is still running and ready to accept new sessions.
</p><p>
To stop the server, right click on the system tray icon and select [Exit].
247 248 249
If you don't have the system tray icon,
navigate to [Preferences] and click [Shutdown],
press [Ctrl]+[C] in the console where the server was started (Windows),
250 251 252
or close the console window.
</p>

Thomas Mueller's avatar
Thomas Mueller committed
253
<h2 id="console_syntax">Special H2 Console Syntax</h2>
254 255
<p>
The H2 Console supports a few built-in commands.
Thomas Mueller's avatar
Thomas Mueller committed
256 257 258
Those are interpreted within the H2 Console, so they work with any database.
Built-in commands need to be at the beginning of a statement (before any remarks),
otherwise they are not parsed correctly. If in doubt, add <code>;</code> before the command.
259
</p>
260
<table class="main">
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    <tr>
        <th>Command(s)</th>
        <th>Description</th>
    </tr>
    <tr>
        <td class="notranslate">
            @autocommit_true;<br />
            @autocommit_false;
        </td>
        <td>
            Enable or disable autocommit.
        </td>
    </tr>
    <tr>
        <td class="notranslate">
            @cancel;
        </td>
        <td>
            Cancel the currently running statement.
        </td>
    </tr>
    <tr>
        <td class="notranslate">
            @columns null null TEST;<br />
            @index_info&nbsp;null&nbsp;null&nbsp;TEST;<br />
            @tables;<br />
            @tables null null TEST;<br />
        </td>
        <td>
Thomas Mueller's avatar
Thomas Mueller committed
290
            Call the corresponding <code>DatabaseMetaData.get</code> method.
291 292
            Patterns are case sensitive (usually identifiers are uppercase).
            For information about the parameters, see the Javadoc documentation.
Thomas Mueller's avatar
Thomas Mueller committed
293
            Missing parameters at the end of the line are set to null. The complete list of metadata commands is:
294
            <code>
Thomas Mueller's avatar
Thomas Mueller committed
295 296 297 298 299
            @attributes, @best_row_identifier, @catalogs, @columns,
            @column_privileges, @cross_references, @exported_keys,
            @imported_keys, @index_info,  @primary_keys, @procedures,
            @procedure_columns, @schemas, @super_tables, @super_types,
            @tables, @table_privileges, @table_types, @type_info, @udts,
Thomas Mueller's avatar
Thomas Mueller committed
300 301
            @version_columns
            </code>
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
        </td>
    </tr>
    <tr>
        <td class="notranslate">
            @edit select * from test;
        </td>
        <td>
            Use an updatable result set.
        </td>
    </tr>
    <tr>
        <td class="notranslate">
            @generated&nbsp;insert&nbsp;into&nbsp;test()&nbsp;values();
        </td>
        <td>
            Show the result of <code>Statement.getGeneratedKeys()</code>.
        </td>
    </tr>
    <tr>
        <td class="notranslate">
            @history;
        </td>
        <td>
Thomas Mueller's avatar
Thomas Mueller committed
325
            List the command history.
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
        </td>
    </tr>
    <tr>
        <td class="notranslate">
            @info;
        </td>
        <td>
            Display the result of various <code>Connection</code> and <code>DatabaseMetaData</code> methods.
        </td>
    </tr>
    <tr>
        <td class="notranslate">
            @list select * from test;
        </td>
        <td>
            Show the result set in list format (each column on its own line, with row numbers).
        </td>
    </tr>
    <tr>
        <td class="notranslate">
            @loop 1000 select ?, ?/*rnd*/;<br />
            @loop 1000 @statement select ?;
        </td>
        <td>
Thomas Mueller's avatar
Thomas Mueller committed
350 351
            Run the statement this many times.
            Parameters (<code>?</code>) are set using a loop from 0 up to x - 1.
352
            Random values are used for each <code>?/*rnd*/</code>.
Thomas Mueller's avatar
Thomas Mueller committed
353
            A Statement object is used instead of a PreparedStatement if <code>@statement</code> is used.
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
            Result sets are read until <code>ResultSet.next()</code> returns <code>false</code>.
            Timing information is printed.
        </td>
    </tr>
    <tr>
        <td class="notranslate">
            @maxrows&nbsp;20;
        </td>
        <td>
            Set the maximum number of rows to display.
        </td>
    </tr>
    <tr>
        <td class="notranslate">
            @memory;
        </td>
        <td>
            Show the used and free memory. This will call <code>System.gc()</code>.
        </td>
    </tr>
    <tr>
        <td class="notranslate">
            @meta&nbsp;select&nbsp;1;
        </td>
        <td>
            List the <code>ResultSetMetaData</code> after running the query.
        </td>
    </tr>
    <tr>
        <td class="notranslate">
            @parameter_meta&nbsp;select&nbsp;?;
        </td>
        <td>
            Show the result of the <code>PreparedStatement.getParameterMetaData()</code> calls.
            The statement is not executed.
        </td>
    </tr>
    <tr>
        <td class="notranslate">
            @prof_start;<br />
            call&nbsp;hash('SHA256',&nbsp;'',&nbsp;1000000);<br />
            @prof_stop;
        </td>
        <td>
Thomas Mueller's avatar
Thomas Mueller committed
398
            Start/stop the built-in profiling tool.
399 400 401 402
            The top 3 stack traces of the statement(s) between start and stop are listed
            (if there are 3).
        </td>
    </tr>
403 404
    <tr>
        <td class="notranslate">
Thomas Mueller's avatar
Thomas Mueller committed
405
            @prof_start;<br />
406 407 408 409
            @sleep 10;<br />
            @prof_stop;
        </td>
        <td>
Thomas Mueller's avatar
Thomas Mueller committed
410
            Sleep for a number of seconds. Used to profile a long running query or
411 412 413
            operation that is running in another session (but in the same process).
        </td>
    </tr>
414 415 416 417 418 419
    <tr>
        <td class="notranslate">
            @transaction_isolation;<br />
            @transaction_isolation&nbsp;2;
        </td>
        <td>
Thomas Mueller's avatar
Thomas Mueller committed
420
            Display (without parameters) or change
421 422 423 424 425
            (with parameters 1, 2, 4, 8) the transaction isolation level.
        </td>
    </tr>
</table>

Thomas Mueller's avatar
Thomas Mueller committed
426
<h2 id="console_settings">Settings of the H2 Console</h2>
427 428
<p>
The settings of the H2 Console are stored in a configuration file
429
called <code>.h2.server.properties</code> in you user home directory.
Thomas Mueller's avatar
Thomas Mueller committed
430
For Windows installations, the user home directory is usually
Thomas Mueller's avatar
Thomas Mueller committed
431 432
<code>C:\Documents and Settings\[username]</code> or
<code>C:\Users\[username]</code>.
433
The configuration file contains the settings of the application and is automatically created when the H2 Console is first started.
Thomas Mueller's avatar
Thomas Mueller committed
434 435 436 437
Supported settings are:
</p>
<ul><li><code>webAllowOthers</code>: allow other computers to connect.
</li><li><code>webPort</code>: the port of the H2 Console
438
</li><li><code>webSSL</code>: use encrypted TLS (HTTPS) connections.
Evgenij Ryazanov's avatar
Evgenij Ryazanov committed
439
</li><li><code>webAdminPassword</code>: password to access preferences and tools of H2 Console.
Thomas Mueller's avatar
Thomas Mueller committed
440 441 442 443 444 445 446 447
</li></ul>
<p>
In addition to those settings, the properties of the last recently used connection
are listed in the form
<code>&lt;number&gt;=&lt;name&gt;|&lt;driver&gt;|&lt;url&gt;|&lt;user&gt;</code>
using the escape character <code>\</code>.
Example:
<code>1=Generic H2 (Embedded)|org.h2.Driver|jdbc\:h2\:~/test|sa</code>
448 449
</p>

Thomas Mueller's avatar
Thomas Mueller committed
450
<h2 id="connecting_using_jdbc">Connecting to a Database using JDBC</h2>
451 452 453 454
<p>
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:
</p>
455
<pre>
456 457
import java.sql.*;
public class Test {
Thomas Mueller's avatar
Thomas Mueller committed
458 459 460 461 462
    public static void main(String[] a)
            throws Exception {
        Connection conn = DriverManager.
            getConnection("jdbc:h2:~/test", "sa", "");
        // add application code here
463
        conn.close();
Thomas Mueller's avatar
Thomas Mueller committed
464
    }
465 466 467
}
</pre>
<p>
468
This code opens a connection (using <code>DriverManager.getConnection()</code>).
469 470 471 472
The driver name is <code>"org.h2.Driver"</code>.
The database URL always needs to start with <code>jdbc:h2:</code>
to be recognized by this database. The second parameter in the <code>getConnection()</code> call
is the user name (<code>sa</code> for System Administrator in this example). The third parameter is the password.
473
In this database, user names are not case sensitive, but passwords are.
474 475
</p>

Thomas Mueller's avatar
Thomas Mueller committed
476
<h2 id="creating_new_databases">Creating New Databases</h2>
477
<p>
478 479 480
By default, if the database specified in the <a href="features.html#database_url">embedded</a> 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.
481
</p>
482
<p>
483
Auto-creation of databases can be disabled, see
484 485
<a href="features.html#database_only_if_exists">Opening a Database Only if it Already Exists</a>.
</p>
486 487 488 489
<p>
H2 Console does not allow creation of databases by default.
If H2 Console is launched with icon in the system tray its context menu can be used to create a new database.
</p>
490

Thomas Mueller's avatar
Thomas Mueller committed
491
<h2 id="using_server">Using the Server</h2>
492
<p>
493 494
H2 currently supports three server: a web server (for the H2 Console),
a TCP server (for client/server connections) and an PG server (for PostgreSQL clients).
Thomas Mueller's avatar
Thomas Mueller committed
495
Please note that only the web server supports browser connections.
496
The servers can be started in different ways, one is using the <code>Server</code> tool.
Thomas Mueller's avatar
Thomas Mueller committed
497
Starting the server doesn't open a database - databases are opened as soon as a client connects.
498 499
</p>

500
<h3>Starting the Server Tool from Command Line</h3>
501
<p>
502
To start the <code>Server</code> tool from the command line with the default settings, run:
503
</p>
504
<pre>
505
java -cp h2*.jar org.h2.tools.Server
506 507
</pre>
<p>
508
This will start the tool with the default options. To get the list of options and default values, run:
509
</p>
510
<pre>
511
java -cp h2*.jar org.h2.tools.Server -?
512 513
</pre>
<p>
514
There are options available to use other ports, and start or not start parts.
515 516 517 518 519 520 521
</p>

<h3>Connecting to the TCP Server</h3>
<p>
To remotely connect to a database using the TCP server, use the following driver and database URL:
</p>
<ul>
522 523
<li>JDBC driver class: <code>org.h2.Driver</code>
</li><li>Database URL: <code>jdbc:h2:tcp://localhost/~/test</code>
524 525 526
</li></ul>
<p>
For details about the database URL, see also in Features.
Thomas Mueller's avatar
Thomas Mueller committed
527
Please note that you can't connection with a web browser to this URL.
Thomas Mueller's avatar
Thomas Mueller committed
528
You can only connect using a H2 client (over JDBC).
529 530
</p>

531
<h3>Starting the TCP Server within an Application</h3>
532
<p>
533
Servers can also be started and stopped from within an application. Sample code:
534
</p>
535
<pre>
536 537 538 539 540 541 542 543 544 545 546
import org.h2.tools.Server;
...
// start the TCP Server
Server server = Server.createTcpServer(args).start();
...
// stop the TCP Server
server.stop();
</pre>

<h3>Stopping a TCP Server from Another Process</h3>
<p>
547
The TCP server can be stopped from another process.
548 549
To stop the server from the command line, run:
</p>
550
<pre>
551 552 553 554 555
java org.h2.tools.Server -tcpShutdown tcp://localhost:9092
</pre>
<p>
To stop the server from a user application, use the following code:
</p>
556
<pre>
557 558 559
org.h2.tools.Server.shutdownTcpServer("tcp://localhost:9094");
</pre>
<p>
560 561 562 563 564
This function will only stop the TCP server.
If other server were started in the same process, they will continue to run.
To avoid recovery when the databases are opened the next time,
all connections to the databases should be closed before calling this method.
To stop a remote server, remote connections must be enabled on the server.
565
Shutting down a TCP server can be protected using the option <code>-tcpPassword</code>
566
(the same password must be used to start and stop the TCP server).
567 568
</p>

Thomas Mueller's avatar
Thomas Mueller committed
569
<h2 id="using_hibernate">Using Hibernate</h2>
570 571
<p>
This database supports Hibernate version 3.1 and newer. You can use the HSQLDB Dialect,
572
or the native H2 Dialect.
573
</p>
Thomas Mueller's avatar
Thomas Mueller committed
574
<p>
Thomas Mueller's avatar
Thomas Mueller committed
575
When using Hibernate, try to use the <code>H2Dialect</code> if possible.
Thomas Mueller's avatar
Thomas Mueller committed
576
When using the <code>H2Dialect</code>,
Thomas Mueller's avatar
Thomas Mueller committed
577 578
compatibility modes such as <code>MODE=MySQL</code> are not supported.
When using such a compatibility mode, use the Hibernate dialect for the
Thomas Mueller's avatar
Thomas Mueller committed
579 580
corresponding database instead of the <code>H2Dialect</code>;
but please note H2 does not support all features of all databases.
Thomas Mueller's avatar
Thomas Mueller committed
581
</p>
582

Thomas Mueller's avatar
Thomas Mueller committed
583
<h2 id="using_toplink">Using TopLink and Glassfish</h2>
584 585
<p>
To use H2 with Glassfish (or Sun AS), set the Datasource Classname to
586
<code>org.h2.jdbcx.JdbcDataSource</code>. You can set this in the GUI
587
at Application Server - Resources - JDBC - Connection Pools,
588 589 590
or by editing the file <code>sun-resources.xml</code>: at element
<code>jdbc-connection-pool</code>, set the attribute
<code>datasource-classname</code> to <code>org.h2.jdbcx.JdbcDataSource</code>.
591 592 593
</p>
<p>
The H2 database is compatible with HSQLDB and PostgreSQL.
594
To take advantage of H2 specific features, use the <code>H2Platform</code>.
595
The source code of this platform is included in H2 at
596
<code>src/tools/oracle/toplink/essentials/platform/database/DatabasePlatform.java.txt</code>.
597 598 599
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:
</p>
600
<pre>
601
&lt;property
Thomas Mueller's avatar
Thomas Mueller committed
602
    name="toplink.target-database"
603
    value="oracle.toplink.essentials.platform.database.H2Platform"/&gt;
604 605
</pre>
<p>
606
In old versions of Glassfish, the property name is <code>toplink.platform.class.name</code>.
607
</p>
Thomas Mueller's avatar
Thomas Mueller committed
608 609 610
<p>
To use H2 within Glassfish, copy the h2*.jar to the directory <code>glassfish/glassfish/lib</code>.
</p>
611

612 613 614 615 616 617 618
<h2 id="using_eclipselink">Using EclipseLink</h2>
<p>
To use H2 in EclipseLink, use the platform class <code>org.eclipse.persistence.platform.database.H2Platform</code>.
If this platform is not available in your version of EclipseLink, you can use the OraclePlatform instead in many case.
See also <a href="http://wiki.eclipse.org/EclipseLink/Development/Incubator/Extensions/H2Platform">H2Platform</a>.
</p>

Thomas Mueller's avatar
Thomas Mueller committed
619 620 621 622 623 624
<h2 id="using_activemq">Using Apache ActiveMQ</h2>
<p>
When using H2 as the backend database for Apache ActiveMQ, please use the <code>TransactDatabaseLocker</code>
instead of the default locking mechanism. Otherwise the database file will grow without bounds. The problem is that the
default locking mechanism uses an uncommitted <code>UPDATE</code> transaction, which keeps the transaction log
from shrinking (causes the database file to grow). Instead of using an <code>UPDATE</code> statement, the <code>TransactDatabaseLocker</code> uses
625 626
<code>SELECT ... FOR UPDATE</code> which is not problematic.
To use it, change the ApacheMQ configuration element <code>&lt;jdbcPersistenceAdapter&gt;</code> element,  property
Thomas Mueller's avatar
Thomas Mueller committed
627
<code>databaseLocker="org.apache.activemq.store.jdbc.adapter.TransactDatabaseLocker"</code>.
628
However, using the MVCC mode will again result in the same problem. Therefore, please do not use the MVCC mode in this case.
Thomas Mueller's avatar
Thomas Mueller committed
629 630 631
Another (more dangerous) solution is to set <code>useDatabaseLock</code> to false.
</p>

Thomas Mueller's avatar
Thomas Mueller committed
632 633
<h2 id="using_netbeans">Using H2 within NetBeans</h2>
<p>
Thomas Mueller's avatar
Thomas Mueller committed
634 635 636 637 638
There is a known issue when using the Netbeans SQL Execution Window:
before executing a query, another query in the form <code>SELECT COUNT(*) FROM &lt;query&gt;</code> is run.
This is a problem for queries that modify state, such as <code>SELECT SEQ.NEXTVAL</code>.
In this case, two sequence values are allocated instead of just one.
</p>
Thomas Mueller's avatar
Thomas Mueller committed
639

640 641
<h2 id="using_jooq">Using H2 with jOOQ</h2>
<p>
Thomas Mueller's avatar
Thomas Mueller committed
642 643 644
jOOQ adds a thin layer on top of JDBC, allowing for type-safe SQL construction,
including advanced SQL, stored procedures and advanced data types.
jOOQ takes your database schema as a base for code generation.
645 646 647 648 649 650 651 652 653 654
If this is your example schema:
</p>
<pre>
CREATE TABLE USER (ID INT, NAME VARCHAR(50));
</pre>
<p>
then run the jOOQ code generator on the command line using this command:
</p>
<pre>
java -cp jooq.jar;jooq-meta.jar;jooq-codegen.jar;h2-1.3.158.jar;.
Thomas Mueller's avatar
Thomas Mueller committed
655
org.jooq.util.GenerationTool /codegen.xml
656 657
</pre>
<p>
Thomas Mueller's avatar
Thomas Mueller committed
658
...where <code>codegen.xml</code> is on the classpath and contains this information
659 660
</p>
<pre>
Thomas Mueller's avatar
Thomas Mueller committed
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?>
&lt;configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-2.3.0.xsd">
    &lt;jdbc>
        &lt;driver>org.h2.Driver&lt;/driver>
        &lt;url>jdbc:h2:~/test&lt;/url>
        &lt;user>sa&lt;/user>
        &lt;password>&lt;/password>
    &lt;/jdbc>
    &lt;generator>
        &lt;name>org.jooq.util.DefaultGenerator&lt;/name>
        &lt;database>
            &lt;name>org.jooq.util.h2.H2Database&lt;/name>
            &lt;includes>.*&lt;/includes>
            &lt;excludes>&lt;/excludes>
            &lt;inputSchema>PUBLIC&lt;/inputSchema>
        &lt;/database>
        &lt;generate>&lt;/generate>
        &lt;target>
            &lt;packageName>org.jooq.h2.generated&lt;/packageName>
            &lt;directory>./src&lt;/directory>
        &lt;/target>
    &lt;/generator>
&lt;/configuration>
684 685 686 687 688 689
</pre>
<p>
Using the generated source, you can query the database as follows:
</p>
<pre>
Factory create = new H2Factory(connection);
Thomas Mueller's avatar
Thomas Mueller committed
690
Result&lt;UserRecord&gt; result =
691
create.selectFrom(USER)
Thomas Mueller's avatar
Thomas Mueller committed
692 693 694
    .where(NAME.like("Johnny%"))
    .orderBy(ID)
    .fetch();
695 696 697
</pre>
<p>
See more details on <a href="http://www.jooq.org">jOOQ Homepage</a>
Thomas Mueller's avatar
Thomas Mueller committed
698
and in the <a href="http://www.jooq.org/tutorial.php">jOOQ Tutorial</a>
699 700
</p>

Thomas Mueller's avatar
Thomas Mueller committed
701
<h2 id="web_applications">Using Databases in Web Applications</h2>
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
<p>
There are multiple ways to access a database from within web
applications. Here are some examples if you use Tomcat or JBoss.
</p>

<h3>Embedded Mode</h3>
<p>
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
718 719
same time, you need to put the database jar in the <code>shared/lib</code> or
<code>server/lib</code> directory. It is a good idea to open the database when the
720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
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).
</p>

<h3>Server Mode</h3>
<p>
The server mode is similar, but it allows you to run the server in another process.
</p>

<h3>Using a Servlet Listener to Start and Stop a Database</h3>
<p>
735
Add the h2*.jar file to your web application, and
736 737
add the following snippet to your web.xml file (between the
<code>context-param</code> and the <code>filter</code> section):
738
</p>
739
<pre>
740 741 742
&lt;listener&gt;
    &lt;listener-class&gt;org.h2.server.web.DbStarter&lt;/listener-class&gt;
&lt;/listener&gt;
743 744
</pre>
<p>
745
For details on how to access the database, see the file <code>DbStarter.java</code>.
746
By default this tool opens an embedded connection
747 748
using the database URL <code>jdbc:h2:~/test</code>,
user name <code>sa</code>, and password <code>sa</code>.
749
If you want to use this connection within your servlet, you can access as follows:
750
</p>
751
<pre>
752 753
Connection conn = getServletContext().getAttribute("connection");
</pre>
754
<p>
755 756
<code>DbStarter</code> can also start the TCP server, however this is disabled by default.
To enable it, use the parameter <code>db.tcpServer</code> in the file <code>web.xml</code>.
757
Here is the complete list of options.
758 759
These options need to be placed between the <code>description</code> tag
and the <code>listener</code> / <code>filter</code> tags:
760
</p>
761
<pre>
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
&lt;context-param&gt;
    &lt;param-name&gt;db.url&lt;/param-name&gt;
    &lt;param-value&gt;jdbc:h2:~/test&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;context-param&gt;
    &lt;param-name&gt;db.user&lt;/param-name&gt;
    &lt;param-value&gt;sa&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;context-param&gt;
    &lt;param-name&gt;db.password&lt;/param-name&gt;
    &lt;param-value&gt;sa&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;context-param&gt;
    &lt;param-name&gt;db.tcpServer&lt;/param-name&gt;
    &lt;param-value&gt;-tcpAllowOthers&lt;/param-value&gt;
&lt;/context-param&gt;
778 779 780
</pre>
<p>
When the web application is stopped, the database connection will be closed automatically.
781
If the TCP server is started within the <code>DbStarter</code>, it will also be stopped automatically.
782 783 784 785 786
</p>

<h3>Using the H2 Console Servlet</h3>
<p>
The H2 Console is a standalone application and includes its own web server, but it can be
787
used as a servlet as well. To do that, include the <code>h2*.jar</code> file in your application, and
788
add the following configuration to your <code>web.xml</code>:
789
</p>
790
<pre>
791 792 793
&lt;servlet&gt;
    &lt;servlet-name&gt;H2Console&lt;/servlet-name&gt;
    &lt;servlet-class&gt;org.h2.server.web.WebServlet&lt;/servlet-class&gt;
Thomas Mueller's avatar
Thomas Mueller committed
794 795 796 797 798 799 800 801 802 803
    &lt;!--
    &lt;init-param&gt;
        &lt;param-name&gt;webAllowOthers&lt;/param-name&gt;
        &lt;param-value&gt;&lt;/param-value&gt;
    &lt;/init-param&gt;
    &lt;init-param&gt;
        &lt;param-name&gt;trace&lt;/param-name&gt;
        &lt;param-value&gt;&lt;/param-value&gt;
    &lt;/init-param&gt;
    --&gt;
804 805 806 807 808 809 810 811
    &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
    &lt;servlet-name&gt;H2Console&lt;/servlet-name&gt;
    &lt;url-pattern&gt;/console/*&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</pre>
<p>
812
For details, see also <code>src/tools/WEB-INF/web.xml</code>.
813 814
</p>
<p>
815
To create a web application with just the H2 Console, run the following command:
816
</p>
817
<pre>
818 819 820
build warConsole
</pre>

Thomas Mueller's avatar
Thomas Mueller committed
821 822 823
<h2 id="android">Android</h2>
<p>
You can use this database on an Android device (using the Dalvik VM) instead of or in addition to SQLite.
Thomas Mueller's avatar
Thomas Mueller committed
824
So far, only very few tests and benchmarks were run, but it seems that performance is similar to SQLite,
Thomas Mueller's avatar
Thomas Mueller committed
825 826
except for opening and closing a database, which is not yet optimized in H2
(H2 takes about 0.2 seconds, and SQLite about 0.02 seconds).
Thomas Mueller's avatar
Thomas Mueller committed
827
Read operations seem to be a bit faster than SQLite, and write operations seem to be slower.
Thomas Mueller's avatar
Thomas Mueller committed
828 829 830 831 832 833
So far, only very few tests have been run, and everything seems to work as expected.
Fulltext search was not yet tested, however the native fulltext search should work.
</p>
<p>
Reasons to use H2 instead of SQLite are:
</p>
Thomas Mueller's avatar
Thomas Mueller committed
834
<ul><li>Full Unicode support including UPPER() and LOWER().
Thomas Mueller's avatar
Thomas Mueller committed
835
</li><li>Streaming API for BLOB and CLOB data.
Thomas Mueller's avatar
Thomas Mueller committed
836 837
</li><li>Fulltext search.
</li><li>Multiple connections.
Thomas Mueller's avatar
Thomas Mueller committed
838
</li><li>User defined functions and triggers.
Thomas Mueller's avatar
Thomas Mueller committed
839
</li><li>Database file encryption.
Thomas Mueller's avatar
Thomas Mueller committed
840
</li><li>Reading and writing CSV files (this feature can be used outside the database as well).
Thomas Mueller's avatar
Thomas Mueller committed
841 842 843 844
</li><li>Referential integrity and check constraints.
</li><li>Better data type and SQL support.
</li><li>In-memory databases, read-only databases, linked tables.
</li><li>Better compatibility with other databases which simplifies porting applications.
Thomas Mueller's avatar
Thomas Mueller committed
845 846
</li><li>Possibly better performance (so far for read operations).
</li><li>Server mode (accessing a database on a different machine over TCP/IP).
Thomas Mueller's avatar
Thomas Mueller committed
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
</li></ul>
<p>
Currently only the JDBC API is supported (it is planned to support the Android database API in future releases).
Both the regular H2 jar file and the smaller <code>h2small-*.jar</code> can be used.
To create the smaller jar file, run the command <code>./build.sh jarSmall</code> (Linux / Mac OS)
or <code>build.bat jarSmall</code> (Windows).
</p>
<p>
The database files needs to be stored in a place that is accessible for the application.
Example:
</p>
<pre>
String url = "jdbc:h2:/data/data/" +
    "com.example.hello" +
    "/data/hello" +
    ";FILE_LOCK=FS" +
    ";PAGE_SIZE=1024" +
    ";CACHE_SIZE=8192";
conn = DriverManager.getConnection(url);
...
</pre>
Thomas Mueller's avatar
Thomas Mueller committed
868 869 870
<p>
Limitations: Using a connection pool is currently not supported, because the required <code>javax.sql.</code> classes are not available on Android.
</p>
Thomas Mueller's avatar
Thomas Mueller committed
871

Thomas Mueller's avatar
Thomas Mueller committed
872
<h2 id="csv">CSV (Comma Separated Values) Support</h2>
873
<p>
874 875
The CSV file support can be used inside the database using the functions
<code>CSVREAD</code> and <code>CSVWRITE</code>,
876
or it can be used outside the database as a standalone tool.
877 878
</p>

Thomas Mueller's avatar
Thomas Mueller committed
879 880 881 882 883 884 885
<h3>Reading a CSV File from Within a Database</h3>
<p>
A CSV file can be read using the function <code>CSVREAD</code>. Example:
</p>
<pre>
SELECT * FROM CSVREAD('test.csv');
</pre>
Thomas Mueller's avatar
Thomas Mueller committed
886 887 888 889 890
<p>
Please note for performance reason, <code>CSVREAD</code> should not be used inside a join.
Instead, import the data first (possibly into a temporary table), create the required indexes
if necessary, and then query this table.
</p>
Thomas Mueller's avatar
Thomas Mueller committed
891 892 893 894 895 896 897 898 899 900 901 902 903 904

<h3>Importing Data from a CSV File</h3>
<p>
A fast way to load or import data (sometimes called 'bulk load') from a CSV file is
to combine table creation with import.
Optionally, the column names and data types can be set when creating the table.
Another option is to use <code>INSERT INTO ... SELECT</code>.
</p>
<pre>
CREATE TABLE TEST AS SELECT * FROM CSVREAD('test.csv');
CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))
    AS SELECT * FROM CSVREAD('test.csv');
</pre>

905 906
<h3>Writing a CSV File from Within a Database</h3>
<p>
907
The built-in function <code>CSVWRITE</code> can be used to create a CSV file from a query.
908 909
Example:
</p>
910
<pre>
911 912 913 914 915 916 917
CREATE TABLE TEST(ID INT, NAME VARCHAR);
INSERT INTO TEST VALUES(1, 'Hello'), (2, 'World');
CALL CSVWRITE('test.csv', 'SELECT * FROM TEST');
</pre>

<h3>Writing a CSV File from a Java Application</h3>
<p>
918
The <code>Csv</code> tool can be used in a Java application even when not using a database at all.
919 920
Example:
</p>
921
<pre>
922
import java.sql.*;
923 924
import org.h2.tools.Csv;
import org.h2.tools.SimpleResultSet;
925 926 927 928 929
public class TestCsv {
    public static void main(String[] args) throws Exception {
        SimpleResultSet rs = new SimpleResultSet();
        rs.addColumn("NAME", Types.VARCHAR, 255, 0);
        rs.addColumn("EMAIL", Types.VARCHAR, 255, 0);
Thomas Mueller's avatar
Thomas Mueller committed
930 931
        rs.addRow("Bob Meier", "bob.meier@abcde.abc");
        rs.addRow("John Jones", "john.jones@abcde.abc");
Thomas Mueller's avatar
Thomas Mueller committed
932
        new Csv().write("data/test.csv", rs, null);
933 934
    }
}
935 936 937 938 939 940 941
</pre>

<h3>Reading a CSV File from a Java Application</h3>
<p>
It is possible to read a CSV file without opening a database.
Example:
</p>
942
<pre>
943
import java.sql.*;
944
import org.h2.tools.Csv;
945 946
public class TestCsv {
    public static void main(String[] args) throws Exception {
Thomas Mueller's avatar
Thomas Mueller committed
947
        ResultSet rs = new Csv().read("data/test.csv", null, null);
948 949 950 951 952 953 954 955 956 957
        ResultSetMetaData meta = rs.getMetaData();
        while (rs.next()) {
            for (int i = 0; i &lt; meta.getColumnCount(); i++) {
                System.out.println(
                    meta.getColumnLabel(i + 1) + ": " +
                    rs.getString(i + 1));
            }
            System.out.println();
        }
        rs.close();
958 959 960 961
    }
}
</pre>

Thomas Mueller's avatar
Thomas Mueller committed
962
<h2 id="upgrade_backup_restore">Upgrade, Backup, and Restore</h2>
963 964 965 966 967 968 969 970 971 972

<h3>Database Upgrade</h3>
<p>
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.
</p>

<h3>Backup using the Script Tool</h3>
<p>
Thomas Mueller's avatar
Thomas Mueller committed
973 974 975 976
The recommended way to backup a database is to create a compressed SQL script file.
This will result in a small, human readable, and database version independent backup.
Creating the script will also verify the checksums of the database file.
The <code>Script</code> tool is ran as follows:
977
</p>
978
<pre>
979 980 981
java org.h2.tools.Script -url jdbc:h2:~/test -user sa -script test.zip -options compression zip
</pre>
<p>
982 983
It is also possible to use the SQL command <code>SCRIPT</code> to create the backup of the database.
For more information about the options, see the SQL command <code>SCRIPT</code>.
984 985 986 987 988 989
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.
</p>

<h3>Restore from a Script</h3>
<p>
990
To restore a database from a SQL script file, you can use the <code>RunScript</code> tool:
991
</p>
992
<pre>
993 994 995
java org.h2.tools.RunScript -url jdbc:h2:~/test -user sa -script test.zip -options compression zip
</pre>
<p>
996
For more information about the options, see the SQL command <code>RUNSCRIPT</code>.
997 998
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.
999
It is also possible to use the SQL command <code>RUNSCRIPT</code> to execute a SQL script.
1000
SQL script files may contain references to other script files, in the form of
1001
<code>RUNSCRIPT</code> commands. However, when using the server mode, the references script files
1002 1003 1004 1005 1006
need to be available on the server side.
</p>

<h3>Online Backup</h3>
<p>
1007
The <code>BACKUP</code> SQL statement and the <code>Backup</code> tool both create a zip file
Thomas Mueller's avatar
Thomas Mueller committed
1008
with the database file. However, the contents of this file are not human readable.
1009
</p><p>
Thomas Mueller's avatar
Thomas Mueller committed
1010
The resulting backup is transactionally consistent, meaning the consistency and atomicity rules apply.
1011
</p>
1012
<pre>
1013 1014 1015
BACKUP TO 'backup.zip'
</pre>
<p>
1016
The <code>Backup</code> tool (<code>org.h2.tools.Backup</code>) can not be used to create a online backup;
1017 1018
the database must not be in use while running this program.
</p>
1019
<p>
Thomas Mueller's avatar
Thomas Mueller committed
1020
Creating a backup by copying the database files while the database is running is not supported,
Thomas Mueller's avatar
Thomas Mueller committed
1021
except if the file systems support creating snapshots.
Thomas Mueller's avatar
Thomas Mueller committed
1022
With other file systems, it can't be guaranteed that the data is copied in the right order.
1023
</p>
1024

Thomas Mueller's avatar
Thomas Mueller committed
1025
<h2 id="command_line_tools">Command Line Tools</h2>
1026 1027 1028 1029
<p>
This database comes with a number of command line tools. To get more information about a tool,
start it with the parameter '-?', for example:
</p>
1030
<pre>
1031 1032 1033 1034 1035
java -cp h2*.jar org.h2.tools.Backup -?
</pre>
<p>
The command line tools are:
</p>
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
<ul><li><code>Backup</code> creates a backup of a database.
</li><li><code>ChangeFileEncryption</code> allows changing the file encryption password or algorithm of a database.
</li><li><code>Console</code> starts the browser based H2 Console.
</li><li><code>ConvertTraceFile</code> converts a .trace.db file to a Java application and SQL script.
</li><li><code>CreateCluster</code> creates a cluster from a standalone database.
</li><li><code>DeleteDbFiles</code> deletes all files belonging to a database.
</li><li><code>Recover</code> helps recovering a corrupted database.
</li><li><code>Restore</code> restores a backup of a database.
</li><li><code>RunScript</code> runs a SQL script against a database.
</li><li><code>Script</code> allows converting a database to a SQL script for backup or migration.
</li><li><code>Server</code> is used in the server mode to start a H2 server.
</li><li><code>Shell</code> is a command line database tool.
1048 1049
</li></ul>
<p>
1050
The tools can also be called from an application by calling the main or another public method.
1051 1052 1053
For details, see the Javadoc documentation.
</p>

1054 1055 1056 1057 1058 1059 1060 1061
<h2 id="shell_tool">The Shell Tool</h2>
<p>
The Shell tool is a simple interactive command line tool. To start it, type:
</p>
<pre>
java -cp h2*.jar org.h2.tools.Shell
</pre>
<p>
1062
You will be asked for a database URL, JDBC driver, user name, and password.
1063
The connection setting can also be set as command line parameters.
1064
After connecting, you will get the list of options.
1065 1066 1067 1068 1069 1070 1071 1072 1073
The built-in commands don't need to end with a semicolon, but
SQL statements are only executed if the line ends with a semicolon <code>;</code>.
This allows to enter multi-line statements:
</p>
<pre>
sql&gt; select * from test
...&gt; where id = 0;
</pre>
<p>
1074
By default, results are printed as a table. For results with many column, consider using the list mode:
1075 1076 1077 1078
</p>
<pre>
sql&gt; list
Result list mode is now on
1079
sql&gt; select * from test;
1080 1081 1082 1083 1084 1085 1086 1087
ID  : 1
NAME: Hello

ID  : 2
NAME: World
(2 rows, 0 ms)
</pre>

Thomas Mueller's avatar
Thomas Mueller committed
1088
<h2 id="open_office">Using OpenOffice Base</h2>
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
<p>
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:
</p>
<ul><li>Start OpenOffice Writer, go to [Tools], [Options]
</li><li>Make sure you have selected a Java runtime environment in OpenOffice.org / Java
</li><li>Click [Class Path...], [Add Archive...]
</li><li>Select your h2 jar file (location is up to you, could be wherever you choose)
</li><li>Click [OK] (as much as needed), stop OpenOffice (including the Quickstarter)
</li><li>Start OpenOffice Base
1100
</li><li>Connect to an existing database; select [JDBC]; [Next]
1101 1102
</li><li>Example datasource URL: <code>jdbc:h2:~/test</code>
</li><li>JDBC driver class: <code>org.h2.Driver</code>
1103 1104 1105 1106 1107 1108 1109 1110 1111
</li></ul>
<p>
Now you can access the database stored in the current users home directory.
</p>
<p>
To use H2 in NeoOffice (OpenOffice without X11):
</p>
<ul><li>In NeoOffice, go to [NeoOffice], [Preferences]
</li><li>Look for the page under [NeoOffice], [Java]
1112
</li><li>Click [Class Path], [Add Archive...]
1113 1114 1115 1116
</li><li>Select your h2 jar file (location is up to you, could be wherever you choose)
</li><li>Click [OK] (as much as needed), restart NeoOffice.
</li></ul>
<p>
1117
Now, when creating a new database using the "Database Wizard" :
1118
</p>
1119 1120
<ul><li>Click [File], [New], [Database].
</li><li>Select [Connect to existing database] and the select [JDBC]. Click next.
1121 1122
</li><li>Example datasource URL: <code>jdbc:h2:~/test</code>
</li><li>JDBC driver class: <code>org.h2.Driver</code>
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
</li></ul>
<p>
Another solution to use H2 in NeoOffice is:
</p>
<ul><li>Package the h2 jar within an extension package
</li><li>Install it as a Java extension in NeoOffice
</li></ul>
<p>
This can be done by create it using the NetBeans OpenOffice plugin.
See also <a href="http://wiki.services.openoffice.org/wiki/Extensions_development_java">Extensions Development</a>.
</p>

Thomas Mueller's avatar
Thomas Mueller committed
1135
<h2 id="web_start">Java Web Start / JNLP</h2>
1136 1137 1138
<p>
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
1139 1140
exception will occur: <code>java.security.AccessControlException</code>:
access denied (<code>java.io.FilePermission ... read</code>).
1141 1142
Example permission tags:
</p>
1143
<pre>
1144 1145 1146
&lt;security&gt;
    &lt;all-permissions/&gt;
&lt;/security&gt;
1147 1148
</pre>

Thomas Mueller's avatar
Thomas Mueller committed
1149
<h2 id="connection_pool">Using a Connection Pool</h2>
1150
<p>
1151 1152 1153
For H2, opening a connection is fast if the database is already open.
Still, using a connection pool improves performance if you open and close connections a lot.
A simple connection pool is included in H2. It is based on the
1154
<a href="http://www.source-code.biz/miniconnectionpoolmanager/">Mini Connection Pool Manager</a>
1155
from Christian d'Heureuse. There are other, more complex, open source connection pools available,
1156
for example the <a href="http://commons.apache.org/proper/commons-dbcp/">Apache Commons DBCP</a>.
1157
For H2, it is about twice as faster to get a connection from the built-in connection pool than to get
1158
one using <code>DriverManager.getConnection()</code>.The build-in connection pool is used as follows:
1159
</p>
1160
<pre>
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
import java.sql.*;
import org.h2.jdbcx.JdbcConnectionPool;
public class Test {
    public static void main(String[] args) throws Exception {
        JdbcConnectionPool cp = JdbcConnectionPool.create(
            "jdbc:h2:~/test", "sa", "sa");
        for (int i = 0; i &lt; args.length; i++) {
            Connection conn = cp.getConnection();
            conn.createStatement().execute(args[i]);
            conn.close();
        }
        cp.dispose();
    }
}
1175 1176
</pre>

Thomas Mueller's avatar
Thomas Mueller committed
1177
<h2 id="fulltext">Fulltext Search</h2>
1178
<p>
1179 1180 1181
H2 includes two fulltext search implementations. One is using Apache Lucene,
and the other (the native implementation) stores the index data in special
tables in the database.
1182 1183
</p>

1184
<h3>Using the Native Fulltext Search</h3>
1185 1186 1187
<p>
To initialize, call:
</p>
1188
<pre>
1189 1190 1191 1192 1193
CREATE ALIAS IF NOT EXISTS FT_INIT FOR "org.h2.fulltext.FullText.init";
CALL FT_INIT();
</pre>
<p>
You need to initialize it in each database where you want to use it.
1194
Afterwards, you can create a fulltext index for a table using:
1195
</p>
1196
<pre>
1197 1198 1199 1200 1201
CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR);
INSERT INTO TEST VALUES(1, 'Hello World');
CALL FT_CREATE_INDEX('PUBLIC', 'TEST', NULL);
</pre>
<p>
Thomas Mueller's avatar
Thomas Mueller committed
1202
PUBLIC is the schema name, TEST is the table name. The list of column names (comma separated) is optional,
1203
in this case all columns are indexed. The index is updated in realtime.
1204 1205
To search the index, use the following query:
</p>
1206
<pre>
1207 1208 1209
SELECT * FROM FT_SEARCH('Hello', 0, 0);
</pre>
<p>
1210 1211
This will produce a result set that contains the query needed to retrieve the data:
</p>
1212
<pre>
1213
QUERY: "PUBLIC"."TEST" WHERE "ID"=1
1214
</pre>
1215
<p>
1216 1217 1218 1219 1220 1221
To drop an index on a table:
</p>
<pre>
CALL FT_DROP_INDEX('PUBLIC', 'TEST');
</pre>
<p>
1222 1223 1224 1225 1226
To get the raw data, use <code>FT_SEARCH_DATA('Hello', 0, 0);</code>.
The result contains the columns <code>SCHEMA</code> (the schema name),
<code>TABLE</code> (the table name),
<code>COLUMNS</code> (an array of column names), and
<code>KEYS</code> (an array of objects).
1227
To join a table, use a join as in:
1228
<code>SELECT T.* FROM FT_SEARCH_DATA('Hello', 0, 0) FT, TEST T
Thomas Mueller's avatar
Thomas Mueller committed
1229
WHERE FT.TABLE='TEST' AND T.ID=FT.KEYS[0];</code>
1230 1231
</p>
<p>
1232 1233
You can also call the index from within a Java application:
</p>
1234
<pre>
1235 1236
org.h2.fulltext.FullText.search(conn, text, limit, offset);
org.h2.fulltext.FullText.searchData(conn, text, limit, offset);
1237 1238
</pre>

1239
<h3>Using the Apache Lucene Fulltext Search</h3>
1240
<p>
1241
To use the Apache Lucene full text search, you need the Lucene library in the classpath.
1242
Apache Lucene 5.5.5 or later version up to 7.6.0 is required.
1243
Newer versions may also work, but were not tested.
1244
How to do that depends on the application; if you use the H2 Console, you can add the Lucene
1245 1246
jar file to the environment variables <code>H2DRIVERS</code> or
<code>CLASSPATH</code>.
1247
To initialize the Lucene fulltext search in a database, call:
1248
</p>
1249
<pre>
1250 1251 1252 1253 1254 1255 1256
CREATE ALIAS IF NOT EXISTS FTL_INIT FOR "org.h2.fulltext.FullTextLucene.init";
CALL FTL_INIT();
</pre>
<p>
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:
</p>
1257
<pre>
1258 1259 1260 1261 1262
CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR);
INSERT INTO TEST VALUES(1, 'Hello World');
CALL FTL_CREATE_INDEX('PUBLIC', 'TEST', NULL);
</pre>
<p>
Thomas Mueller's avatar
Thomas Mueller committed
1263
PUBLIC is the schema name, TEST is the table name. The list of column names (comma separated) is optional,
1264
in this case all columns are indexed. The index is updated in realtime. To search the index,
1265
use the following query:
1266
</p>
1267
<pre>
1268 1269 1270
SELECT * FROM FTL_SEARCH('Hello', 0, 0);
</pre>
<p>
1271 1272
This will produce a result set that contains the query needed to retrieve the data:
</p>
1273
<pre>
1274
QUERY: "PUBLIC"."TEST" WHERE "ID"=1
1275
</pre>
1276
<p>
Thomas Mueller's avatar
Thomas Mueller committed
1277 1278
To drop an index on a table
(be warned that this will re-index all of the full-text indices for the entire database):
1279 1280 1281 1282 1283
</p>
<pre>
CALL FTL_DROP_INDEX('PUBLIC', 'TEST');
</pre>
<p>
1284 1285 1286 1287 1288 1289
To get the raw data, use <code>FTL_SEARCH_DATA('Hello', 0, 0);</code>.
The result contains the columns <code>SCHEMA</code> (the schema name),
<code>TABLE</code> (the table name),
<code>COLUMNS</code> (an array of column names),
and <code>KEYS</code> (an array of objects). To join a table, use a join as in:
<code>SELECT T.* FROM FTL_SEARCH_DATA('Hello', 0, 0) FT, TEST T
Thomas Mueller's avatar
Thomas Mueller committed
1290
WHERE FT.TABLE='TEST' AND T.ID=FT.KEYS[0];</code>
1291 1292
</p>
<p>
1293 1294
You can also call the index from within a Java application:
</p>
1295
<pre>
1296 1297
org.h2.fulltext.FullTextLucene.search(conn, text, limit, offset);
org.h2.fulltext.FullTextLucene.searchData(conn, text, limit, offset);
1298
</pre>
Thomas Mueller's avatar
Thomas Mueller committed
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
<p>
The Lucene fulltext search supports searching in specific column only.
Column names must be uppercase (except if the original columns are double quoted).
For column names starting with an underscore (_), another underscore needs to be added.
Example:
</p>
<pre>
CREATE ALIAS IF NOT EXISTS FTL_INIT FOR "org.h2.fulltext.FullTextLucene.init";
CALL FTL_INIT();
DROP TABLE IF EXISTS TEST;
CREATE TABLE TEST(ID INT PRIMARY KEY, FIRST_NAME VARCHAR, LAST_NAME VARCHAR);
CALL FTL_CREATE_INDEX('PUBLIC', 'TEST', NULL);
INSERT INTO TEST VALUES(1, 'John', 'Wayne');
INSERT INTO TEST VALUES(2, 'Elton', 'John');
SELECT * FROM FTL_SEARCH_DATA('John', 0, 0);
SELECT * FROM FTL_SEARCH_DATA('LAST_NAME:John', 0, 0);
CALL FTL_DROP_ALL();
</pre>
1317

Thomas Mueller's avatar
Thomas Mueller committed
1318
<h2 id="user_defined_variables">User-Defined Variables</h2>
1319
<p>
1320
This database supports user-defined variables. Variables start with <code>@</code> and can be used wherever
1321 1322
expressions or parameters are allowed. Variables are not persisted and session scoped, that means only visible
from within the session in which they are defined. A value is usually assigned using the SET command:
1323
</p>
1324
<pre>
1325 1326 1327
SET @USER = 'Joe';
</pre>
<p>
1328
The value can also be changed using the SET() method. This is useful in queries:
1329
</p>
1330
<pre>
1331 1332 1333 1334
SET @TOTAL = NULL;
SELECT X, SET(@TOTAL, IFNULL(@TOTAL, 1.) * X) F FROM SYSTEM_RANGE(1, 50);
</pre>
<p>
1335
Variables that are not set evaluate to <code>NULL</code>.
1336
The data type of a user-defined variable is the data type
1337 1338
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.
Thomas Mueller's avatar
Thomas Mueller committed
1339
Rolling back a transaction does not affect the value of a user-defined variable.
1340 1341
</p>

Thomas Mueller's avatar
Thomas Mueller committed
1342
<h2 id="date_time">Date and Time</h2>
1343 1344 1345
<p>
Date, time and timestamp values support ISO 8601 formatting, including time zone:
</p>
1346
<pre>
1347 1348 1349 1350
CALL TIMESTAMP '2008-01-01 12:00:00+01:00';
</pre>
<p>
If the time zone is not set, the value is parsed using the current time zone setting of the system.
1351 1352 1353 1354 1355
Date and time information is stored in H2 database files with or without time zone information depending on used data type.
</p>
<ul>
<li>
With TIMESTAMP data type if the database is opened using another system time zone, the date and time will be the same.
Thomas Mueller's avatar
Thomas Mueller committed
1356 1357 1358
That means if you store the value '2000-01-01 12:00:00' in one time zone, then close the database
and open the database again in a different time zone, you will also get '2000-01-01 12:00:00'.
Please note that changing the time zone after the H2 driver is loaded is not supported.
1359 1360 1361 1362 1363 1364 1365 1366 1367
</li>
<li>
With TIMESTAMP WITH TIME ZONE data type time zone offset is stored and if you store the value
'2008-01-01 12:00:00+01:00' it remains the same even if you close and reopen the database with a different time zone.
If you store the value with specified time zone name like '2008-01-01 12:00:00 Europe/Berlin' this name will be
converted to time zone offset.
Names of time zones are not stored.
</li>
</ul>
1368

Thomas Mueller's avatar
Thomas Mueller committed
1369
<h2 id="spring">Using Spring</h2>
1370
<h3>Using the TCP Server</h3>
1371
<p>
1372
Use the following configuration to start and stop the H2 TCP server using the Spring Framework:
1373
</p>
1374
<pre>
Thomas Mueller's avatar
Thomas Mueller committed
1375
&lt;bean id = "org.h2.tools.Server"
1376 1377 1378 1379
            class="org.h2.tools.Server"
            factory-method="createTcpServer"
            init-method="start"
            destroy-method="stop"&gt;
Thomas Mueller's avatar
Thomas Mueller committed
1380
    &lt;constructor-arg value="-tcp,-tcpAllowOthers,-tcpPort,8043" /&gt;
1381 1382 1383
&lt;/bean&gt;
</pre>
<p>
1384
The <code>destroy-method</code> will help prevent exceptions on hot-redeployment or when restarting the server.
1385 1386
</p>

1387 1388
<h2 id="osgi">OSGi</h2>
<p>
1389
The standard H2 jar can be dropped in as a bundle in an OSGi container.
Thomas Mueller's avatar
Thomas Mueller committed
1390 1391 1392
H2 implements the JDBC Service defined in OSGi Service Platform Release 4 Version 4.2 Enterprise Specification.
The H2 Data Source Factory service is registered with the following properties:
<code>OSGI_JDBC_DRIVER_CLASS=org.h2.Driver</code>
1393
and <code>OSGI_JDBC_DRIVER_NAME=H2 JDBC Driver</code>.
Thomas Mueller's avatar
Thomas Mueller committed
1394
The <code>OSGI_JDBC_DRIVER_VERSION</code>
1395 1396 1397
property reflects the version of the driver as is.
</p>
<p>
1398
The following standard configuration properties are supported:
Thomas Mueller's avatar
Thomas Mueller committed
1399
<code>JDBC_USER, JDBC_PASSWORD, JDBC_DESCRIPTION, JDBC_DATASOURCE_NAME, JDBC_NETWORK_PROTOCOL, JDBC_URL, JDBC_SERVER_NAME, JDBC_PORT_NUMBER</code>.
1400
Any other standard property will be rejected.
Thomas Mueller's avatar
Thomas Mueller committed
1401
Non-standard properties will be passed on to H2 in the connection URL.
1402 1403
</p>

Thomas Mueller's avatar
Thomas Mueller committed
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
<h2 id="jmx">Java Management Extension (JMX)</h2>
<p>
Management over JMX is supported, but not enabled by default.
To enable JMX, append <code>;JMX=TRUE</code> to the database URL when opening the database.
Various tools support JMX, one such tool is the <code>jconsole</code>.
When opening the <code>jconsole</code>, connect to the process where the database is open
(when using the server mode, you need to connect to the server process). Then go to the <code>MBeans</code> section.
Under <code>org.h2</code> you will find one entry per database. The object name of the entry
is the database short name, plus the path (each colon is replaced with an underscore character).
</p>
<p>
The following attributes and operations are supported:
</p>
<ul><li><code>CacheSize</code>: the cache size currently in use in KB.
</li><li><code>CacheSizeMax</code> (read/write): the maximum cache size in KB.
</li><li><code>Exclusive</code>: whether this database is open in exclusive mode or not.
</li><li><code>FileReadCount</code>: the number of file read operations since the database was opened.
</li><li><code>FileSize</code>: the file size in KB.
</li><li><code>FileWriteCount</code>: the number of file write operations since the database was opened.
</li><li><code>FileWriteCountTotal</code>: the number of file write operations since the database was created.
</li><li><code>LogMode</code> (read/write): the current transaction log mode. See <code>SET LOG</code> for details.
</li><li><code>Mode</code>: the compatibility mode (<code>REGULAR</code> if no compatibility mode is used).
</li><li><code>MultiThreaded</code>: true if multi-threaded is enabled.
</li><li><code>Mvcc</code>: true if <code>MVCC</code> is enabled.
</li><li><code>ReadOnly</code>: true if the database is read-only.
</li><li><code>TraceLevel</code> (read/write): the file trace level.
</li><li><code>Version</code>: the database version in use.
</li><li><code>listSettings</code>: list the database settings.
</li><li><code>listSessions</code>: list the open sessions, including currently executing statement (if any) and locked tables (if any).
</li></ul>
Thomas Mueller's avatar
Thomas Mueller committed
1434 1435 1436 1437
<p>
To enable JMX, you may need to set the system properties <code>com.sun.management.jmxremote</code> and
<code>com.sun.management.jmxremote.port</code> as required by the JVM.
</p>
1438 1439
<!-- [close] { --></div></td></tr></table><!-- } --><!-- analytics --></body></html>