tutorial.html 36.7 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
Copyright 2004-2010 H2 Group. Multiple-Licensed under the H2 License, Version 1.0,
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
and under the Eclipse Public License, Version 1.0
(http://h2database.com/html/license.html).
Initial Developer: H2 Group
-->
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head><meta http-equiv="Content-Type" content="text/html;charset=utf-8" /><title>
Tutorial
</title><link rel="stylesheet" type="text/css" href="stylesheet.css" />
<!-- [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">
<!-- } -->

<h1>Tutorial</h1>
<a href="#tutorial_starting_h2_console">
    Starting and Using the H2 Console</a><br />
<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 />
33 34
<a href="#using_eclipselink">
    Using EclipseLink</a><br />
35 36 37 38 39 40 41 42
<a href="#web_applications">
    Using Databases in Web Applications</a><br />
<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 />
43
<a href="#shell_tool">
44
    The Shell Tool</a><br />
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
<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 />

Thomas Mueller's avatar
Thomas Mueller committed
60
<h2 id="tutorial_starting_h2_console">Starting and Using the H2 Console</h2>
61
<p>
62
The H2 Console application lets you access a SQL database using a browser interface.
63 64 65 66 67 68 69 70
This can be a H2 database, or another database that supports the JDBC API.
</p>
<img src="images/console.png" alt="Web Browser - H2 Console Server - H2 Database" />
<p>
This is a client / server application, so both a server and a client (a browser) are required to run it.
</p><p>
Depending on your platform and environment, there are multiple ways to start the application:
</p>
71 72
<table>
<tr><th>OS</th><th>Start</th></tr>
73
<tr>
Thomas Mueller's avatar
Thomas Mueller committed
74 75
    <td>Windows</td>
    <td>
76
    Click [Start], [All Programs], [H2], and [H2 Console (Command Line)]<br />
Thomas Mueller's avatar
Thomas Mueller committed
77
    When using the Sun JDK 1.5, a window with the title 'H2 Console ' should appear.
78 79 80 81
    When using the Sun JDK 1.6, an icon will be added to the system tray:
    <img src="images/db-16.png" alt="[H2 icon]" /><br />
    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).
82
    A browser window should open and point to the Login page at <code>http://localhost:8082</code>.
Thomas Mueller's avatar
Thomas Mueller committed
83
    </td>
84 85
</tr>
<tr>
Thomas Mueller's avatar
Thomas Mueller committed
86 87
    <td>Windows</td>
    <td>
88 89
    Open a file browser, navigate to <code>h2/bin</code>, and
    double click on <code>h2.bat</code>.<br />
90 91
    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
92
    (URL: <code>http://localhost:8082</code>).
Thomas Mueller's avatar
Thomas Mueller committed
93
    </td>
94
</tr>
95 96 97
<tr>
    <td>Any</td>
    <td>
98 99
    Double click on the <code>h2*.jar</code> file.
    This only works if the <code>.jar</code> suffix is associated with java.
100 101
    </td>
</tr>
102
<tr>
Thomas Mueller's avatar
Thomas Mueller committed
103 104
    <td>Any</td>
    <td>
105 106
    Open a console window, navigate to the directory <code>h2/bin</code> and type:
    <pre>java -cp h2*.jar org.h2.tools.Server</pre>
Thomas Mueller's avatar
Thomas Mueller committed
107
    </td>
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
</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
connecting over the IP address. A workaround is to connect using localhost, however this only works
on the local machine.
</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>
131
To find out which version of Java is installed, open a command prompt and type:
132
</p>
133
<pre>
134 135 136 137 138 139
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>

140
<h3>Error Message 'Port may be in use'</h3>
141 142 143
<p>
You can only start one instance of the H2 Console,
otherwise you will get the following error message:
144
"The Web server could not be started. Possible cause: another server is already running...".
145 146 147 148 149 150 151
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>
If the port is in use by another application, you may want to start the H2 Console on a different port.
152 153
This can be done by changing the port in the file <code>.h2.server.properties</code>. This file is stored
in the user directory (for Windows, this is usually in <code>Documents and Settings/&lt;username&gt;</code>).
154 155 156 157 158 159
The relevant entry is webPort.
</p>

<h3>Connecting to the Server using a Browser</h3>
<p>
If the server started successfully, you can connect to it using a web browser.
160
JavaScript needs to be enabled.
161
If you started the server on the same computer as the browser, open the URL <code>http://localhost:8082</code>.
162
If you want to connect to the application from another computer, you need to provide the IP address of the server, for example:
163 164
<code>http://192.168.0.2:8082</code>.
If you enabled SSL on the server side, the URL needs to start with <code>https://</code>.
165 166 167 168 169 170 171 172 173 174 175 176 177 178
</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.
Set the JDBC driver class of your database, the JDBC URL, user name and password.
If you are done, click [Connect].
</p><p>
179 180
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>).
181 182 183 184 185 186 187 188 189 190
</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
191 192
Additional database drivers to connect to other databases (MySQL, PostgreSQL, HSQLDB,...) 
can be registered by adding the Jar file location of the driver to the environment
193
variables <code>H2DRIVERS</code> or <code>CLASSPATH</code>.
194
Example (Windows): to add the database driver library
195 196 197
<code>C:\Programs\hsqldb\lib\hsqldb.jar</code>, set the environment variable
<code>H2DRIVERS</code> to
<code>C:\Programs\hsqldb\lib\hsqldb.jar</code>.
198
</p><p>
199 200
Multiple drivers can be set; each entry needs to be separated with a <code>;</code> (Windows)
or <code>:</code> (other operating systems).
201 202 203
Spaces in the path names are supported. The settings must not be quoted.
</p>

204
<h3>Using the H2 Console</h3>
205
<p>
206
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.
207 208 209 210 211 212 213
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.
</p>

<h3>Inserting Table Names or Column Names</h3>
<p>
The table name and column names can be inserted in the script by clicking them in the tree.
214
If you click on a table while the query is empty, then <code>SELECT * FROM ...</code> is added as well.
215
While typing a query, the table that was used is automatically expanded in the tree.
216
For example if you type <code>SELECT * FROM TEST T WHERE T.</code> then the table TEST is automatically expanded in the tree.
217 218 219 220
</p>

<h3>Disconnecting and Stopping the Application</h3>
<p>
221
To log out of the database, click 'Disconnect' in the toolbar panel.
222 223 224
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].
225 226 227
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),
228 229 230
or close the console window.
</p>

Thomas Mueller's avatar
Thomas Mueller committed
231
<h2 id="console_settings">Settings of the H2 Console</h2>
232 233
<p>
The settings of the H2 Console are stored in a configuration file
234 235
called <code>.h2.server.properties</code> in you user home directory.
For Windows installations, the user home directory is usually <code>C:\Documents and Settings\[username]</code>.
236 237 238
The configuration file contains the settings of the application and is automatically created when the H2 Console is first started.
</p>

Thomas Mueller's avatar
Thomas Mueller committed
239
<h2 id="connecting_using_jdbc">Connecting to a Database using JDBC</h2>
240 241 242 243
<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>
244
<pre>
245 246
import java.sql.*;
public class Test {
Thomas Mueller's avatar
Thomas Mueller committed
247 248 249 250 251 252
    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
253
        conn.close();
Thomas Mueller's avatar
Thomas Mueller committed
254
    }
255 256 257
}
</pre>
<p>
258 259 260 261 262 263
This code first loads the driver (<code>Class.forName(...)</code>)
and then opens a connection (using <code>DriverManager.getConnection()</code>).
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.
264
In this database, user names are not case sensitive, but passwords are.
265 266
</p>

Thomas Mueller's avatar
Thomas Mueller committed
267
<h2 id="creating_new_databases">Creating New Databases</h2>
268 269 270 271 272
<p>
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.
</p>
273 274 275 276
<p>
Auto-creating new database can be disabled, see
<a href="features.html#database_only_if_exists">Opening a Database Only if it Already Exists</a>.
</p>
277

Thomas Mueller's avatar
Thomas Mueller committed
278
<h2 id="using_server">Using the Server</h2>
279
<p>
280 281
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).
282
The servers can be started in different ways, one is using the <code>Server</code> tool.
283 284
</p>

285
<h3>Starting the Server Tool from Command Line</h3>
286
<p>
287
To start the <code>Server</code> tool from the command line with the default settings, run:
288
</p>
289
<pre>
290
java -cp h2*.jar org.h2.tools.Server
291 292
</pre>
<p>
293
This will start the tool with the default options. To get the list of options and default values, run:
294
</p>
295
<pre>
296
java -cp h2*.jar org.h2.tools.Server -?
297 298
</pre>
<p>
299
There are options available to use other ports, and start or not start parts.
300 301 302 303 304 305 306
</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>
307 308
<li>JDBC driver class: <code>org.h2.Driver</code>
</li><li>Database URL: <code>jdbc:h2:tcp://localhost/~/test</code>
309 310 311 312 313
</li></ul>
<p>
For details about the database URL, see also in Features.
</p>

314
<h3>Starting the TCP Server within an Application</h3>
315
<p>
316
Servers can also be started and stopped from within an application. Sample code:
317
</p>
318
<pre>
319 320 321 322 323 324 325 326 327 328 329
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>
330
The TCP server can be stopped from another process.
331 332
To stop the server from the command line, run:
</p>
333
<pre>
334 335 336 337 338
java org.h2.tools.Server -tcpShutdown tcp://localhost:9092
</pre>
<p>
To stop the server from a user application, use the following code:
</p>
339
<pre>
340 341 342
org.h2.tools.Server.shutdownTcpServer("tcp://localhost:9094");
</pre>
<p>
343 344 345 346 347
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.
348
Shutting down a TCP server can be protected using the option <code>-tcpPassword</code>
349
(the same password must be used to start and stop the TCP server).
350 351
</p>

Thomas Mueller's avatar
Thomas Mueller committed
352
<h2 id="using_hibernate">Using Hibernate</h2>
353 354 355 356 357
<p>
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
<a href="http://opensource.atlassian.com/projects/hibernate/browse/HHH-3401">patch
for Hibernate</a> has been submitted. The dialect for the newest version of Hibernate
358 359
is also available at <code>src/tools/org/hibernate/dialect/H2Dialect.java.txt</code>.
You can rename it to <code>H2Dialect.java</code> and include this as a patch in your application.
360 361
</p>

Thomas Mueller's avatar
Thomas Mueller committed
362
<h2 id="using_toplink">Using TopLink and Glassfish</h2>
363 364
<p>
To use H2 with Glassfish (or Sun AS), set the Datasource Classname to
365
<code>org.h2.jdbcx.JdbcDataSource</code>. You can set this in the GUI
366
at Application Server - Resources - JDBC - Connection Pools,
367 368 369
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>.
370 371 372
</p>
<p>
The H2 database is compatible with HSQLDB and PostgreSQL.
373
To take advantage of H2 specific features, use the <code>H2Platform</code>.
374
The source code of this platform is included in H2 at
375
<code>src/tools/oracle/toplink/essentials/platform/database/DatabasePlatform.java.txt</code>.
376 377 378
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>
379
<pre>
380
&lt;property
Thomas Mueller's avatar
Thomas Mueller committed
381
    name="toplink.target-database"
382
    value="oracle.toplink.essentials.platform.database.H2Platform"/&gt;
383 384
</pre>
<p>
385
In old versions of Glassfish, the property name is <code>toplink.platform.class.name</code>.
386 387
</p>

388 389 390 391 392 393 394
<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
395
<h2 id="web_applications">Using Databases in Web Applications</h2>
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
<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
412 413
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
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
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>
429
Add the h2*.jar file to your web application, and
430 431
add the following snippet to your web.xml file (between the
<code>context-param</code> and the <code>filter</code> section):
432
</p>
433
<pre>
434 435 436
&lt;listener&gt;
    &lt;listener-class&gt;org.h2.server.web.DbStarter&lt;/listener-class&gt;
&lt;/listener&gt;
437 438
</pre>
<p>
439
For details on how to access the database, see the file <code>DbStarter.java</code>.
440
By default this tool opens an embedded connection
441 442
using the database URL <code>jdbc:h2:~/test</code>,
user name <code>sa</code>, and password <code>sa</code>.
443
If you want to use this connection within your servlet, you can access as follows:
444
</p>
445
<pre>
446 447
Connection conn = getServletContext().getAttribute("connection");
</pre>
448
<p>
449 450
<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>.
451
Here is the complete list of options.
452 453
These options need to be placed between the <code>description</code> tag
and the <code>listener</code> / <code>filter</code> tags:
454
</p>
455
<pre>
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
&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;
472 473 474
</pre>
<p>
When the web application is stopped, the database connection will be closed automatically.
475
If the TCP server is started within the <code>DbStarter</code>, it will also be stopped automatically.
476 477 478 479 480
</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
481 482
used as a servlet as well. To do that, include the the <code>h2*.jar</code> file in your application, and
add the following configuration to your <code>web.xml</code>:
483
</p>
484
<pre>
485 486 487
&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
488 489 490 491 492 493 494 495 496 497
    &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;
498 499 500 501 502 503 504 505
    &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>
506
For details, see also <code>src/tools/WEB-INF/web.xml</code>.
507 508
</p>
<p>
509
To create a web application with just the H2 Console, run the following command:
510
</p>
511
<pre>
512 513 514
build warConsole
</pre>

Thomas Mueller's avatar
Thomas Mueller committed
515
<h2 id="csv">CSV (Comma Separated Values) Support</h2>
516
<p>
517 518
The CSV file support can be used inside the database using the functions
<code>CSVREAD</code> and <code>CSVWRITE</code>,
519
or it can be used outside the database as a standalone tool.
520 521 522 523
</p>

<h3>Writing a CSV File from Within a Database</h3>
<p>
524
The built-in function <code>CSVWRITE</code> can be used to create a CSV file from a query.
525 526
Example:
</p>
527
<pre>
528 529 530 531 532 533 534
CREATE TABLE TEST(ID INT, NAME VARCHAR);
INSERT INTO TEST VALUES(1, 'Hello'), (2, 'World');
CALL CSVWRITE('test.csv', 'SELECT * FROM TEST');
</pre>

<h3>Reading a CSV File from Within a Database</h3>
<p>
535
A CSV file can be read using the function <code>CSVREAD</code>. Example:
536
</p>
537
<pre>
538 539 540 541 542
SELECT * FROM CSVREAD('test.csv');
</pre>

<h3>Writing a CSV File from a Java Application</h3>
<p>
543
The <code>Csv</code> tool can be used in a Java application even when not using a database at all.
544 545
Example:
</p>
546
<pre>
547
import java.sql.*;
548 549
import org.h2.tools.Csv;
import org.h2.tools.SimpleResultSet;
550 551 552 553 554
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
555 556
        rs.addRow("Bob Meier", "bob.meier@abcde.abc");
        rs.addRow("John Jones", "john.jones@abcde.abc");
557 558 559
        Csv.getInstance().write("data/test.csv", rs, null);
    }
}
560 561 562 563 564 565 566
</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>
567
<pre>
568
import java.sql.*;
569
import org.h2.tools.Csv;
570 571 572 573 574 575 576 577 578 579 580 581 582 583
public class TestCsv {
    public static void main(String[] args) throws Exception {
        ResultSet rs = Csv.getInstance().
            read("data/test.csv", null, null);
        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();
584 585 586 587
    }
}
</pre>

Thomas Mueller's avatar
Thomas Mueller committed
588
<h2 id="upgrade_backup_restore">Upgrade, Backup, and Restore</h2>
589 590 591 592 593 594 595 596 597 598 599 600 601

<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>
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.
602
This can be done using the <code>Script</code> tool:
603
</p>
604
<pre>
605 606 607
java org.h2.tools.Script -url jdbc:h2:~/test -user sa -script test.zip -options compression zip
</pre>
<p>
608 609
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>.
610 611 612 613 614 615
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>
616
To restore a database from a SQL script file, you can use the <code>RunScript</code> tool:
617
</p>
618
<pre>
619 620 621
java org.h2.tools.RunScript -url jdbc:h2:~/test -user sa -script test.zip -options compression zip
</pre>
<p>
622
For more information about the options, see the SQL command <code>RUNSCRIPT</code>.
623 624
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.
625
It is also possible to use the SQL command <code>RUNSCRIPT</code> to execute a SQL script.
626
SQL script files may contain references to other script files, in the form of
627
<code>RUNSCRIPT</code> commands. However, when using the server mode, the references script files
628 629 630 631 632
need to be available on the server side.
</p>

<h3>Online Backup</h3>
<p>
633
The <code>BACKUP</code> SQL statement and the <code>Backup</code> tool both create a zip file
634
with all database files. However, the contents of this file are not human readable.
635 636
</p><p>
Unlike than the SCRIPT statement, the <code>BACKUP</code> statement does not lock the
Thomas Mueller's avatar
Thomas Mueller committed
637
database objects when using the multi-threaded mode, and therefore does not block other users.
638
The resulting backup is transactionally consistent:
639
</p>
640
<pre>
641 642 643
BACKUP TO 'backup.zip'
</pre>
<p>
644
The <code>Backup</code> tool (<code>org.h2.tools.Backup</code>) can not be used to create a online backup;
645 646
the database must not be in use while running this program.
</p>
647
<p>
Thomas Mueller's avatar
Thomas Mueller committed
648
Creating a backup by copying the database files while the database is running is not supported,
649
except if the file systems support creating snapshots. The problem is that it can't
650 651
be guaranteed that the data is copied in the right order.
</p>
652

Thomas Mueller's avatar
Thomas Mueller committed
653
<h2 id="command_line_tools">Command Line Tools</h2>
654 655 656 657
<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>
658
<pre>
659 660 661 662 663
java -cp h2*.jar org.h2.tools.Backup -?
</pre>
<p>
The command line tools are:
</p>
664 665 666 667 668 669 670 671 672 673 674 675
<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.
676 677
</li></ul>
<p>
678
The tools can also be called from an application by calling the main or another public method.
679 680 681
For details, see the Javadoc documentation.
</p>

682 683 684 685 686 687 688 689
<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>
690
You will be asked for a database URL, JDBC driver, user name, and password.
691
The connection setting can also be set as command line parameters.
692
After connecting, you will get the list of options.
693 694 695 696 697 698 699 700 701
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>
702
By default, results are printed as a table. For results with many column, consider using the list mode:
703 704 705 706
</p>
<pre>
sql&gt; list
Result list mode is now on
707
sql&gt; select * from test;
708 709 710 711 712 713 714 715
ID  : 1
NAME: Hello

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

Thomas Mueller's avatar
Thomas Mueller committed
716
<h2 id="open_office">Using OpenOffice Base</h2>
717 718 719 720 721 722 723 724 725 726 727
<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
728
</li><li>Connect to an existing database; select [JDBC]; [Next]
729 730
</li><li>Example datasource URL: <code>jdbc:h2:~/test</code>
</li><li>JDBC driver class: <code>org.h2.Driver</code>
731 732 733 734 735 736 737 738 739
</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]
740
</li><li>Click [Class Path], [Add Archive...]
741 742 743 744
</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>
745
Now, when creating a new database using the "Database Wizard" :
746
</p>
747 748
<ul><li>Click [File], [New], [Database].
</li><li>Select [Connect to existing database] and the select [JDBC]. Click next.
749 750
</li><li>Example datasource URL: <code>jdbc:h2:~/test</code>
</li><li>JDBC driver class: <code>org.h2.Driver</code>
751 752 753 754 755 756 757 758 759 760 761 762
</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
763
<h2 id="web_start">Java Web Start / JNLP</h2>
764 765 766
<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
767 768
exception will occur: <code>java.security.AccessControlException</code>:
access denied (<code>java.io.FilePermission ... read</code>).
769 770
Example permission tags:
</p>
771
<pre>
772 773 774
&lt;security&gt;
    &lt;all-permissions/&gt;
&lt;/security&gt;
775 776
</pre>

Thomas Mueller's avatar
Thomas Mueller committed
777
<h2 id="connection_pool">Using a Connection Pool</h2>
778
<p>
779 780 781
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
782
<a href="http://www.source-code.biz/snippets/java/8.htm">Mini Connection Pool Manager</a>
783 784
from Christian d'Heureuse. There are other, more complex, open source connection pools available,
for example the <a href="http://jakarta.apache.org/commons/dbcp/">Apache Commons DBCP</a>.
785
For H2, it is about twice as faster to get a connection from the built-in connection pool than to get
786
one using <code>DriverManager.getConnection()</code>.The build-in connection pool is used as follows:
787
</p>
788
<pre>
789 790 791 792 793 794 795 796 797 798 799 800 801 802
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();
    }
}
803 804
</pre>

Thomas Mueller's avatar
Thomas Mueller committed
805
<h2 id="fulltext">Fulltext Search</h2>
806
<p>
807 808 809
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.
810 811
</p>

812
<h3>Using the Native Fulltext Search</h3>
813 814 815
<p>
To initialize, call:
</p>
816
<pre>
817 818 819 820 821
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.
822
Afterwards, you can create a fulltext index for a table using:
823
</p>
824
<pre>
825 826 827 828 829
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>
830
PUBLIC is the schema name, TEST is the table name. The list of column names (column separated) is optional,
831
in this case all columns are indexed. The index is updated in realtime.
832 833
To search the index, use the following query:
</p>
834
<pre>
835 836 837
SELECT * FROM FT_SEARCH('Hello', 0, 0);
</pre>
<p>
838 839
This will produce a result set that contains the query needed to retrieve the data:
</p>
840
<pre>
841
QUERY: "PUBLIC"."TEST" WHERE "ID"=1
842
</pre>
843
<p>
844 845 846 847 848
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).
849
To join a table, use a join as in:
850
<code>SELECT T.* FROM FT_SEARCH_DATA('Hello', 0, 0) FT, TEST T
Thomas Mueller's avatar
Thomas Mueller committed
851
WHERE FT.TABLE='TEST' AND T.ID=FT.KEYS[0];</code>
852 853
</p>
<p>
854 855
You can also call the index from within a Java application:
</p>
856
<pre>
857 858
org.h2.fulltext.FullText.search(conn, text, limit, offset);
org.h2.fulltext.FullText.searchData(conn, text, limit, offset);
859 860 861 862 863
</pre>

<h3>Using the Lucene Fulltext Search</h3>
<p>
To use the Lucene full text search, you need the Lucene library in the classpath.
864
How to do that depends on the application; if you use the H2 Console, you can add the Lucene
865 866
jar file to the environment variables <code>H2DRIVERS</code> or
<code>CLASSPATH</code>.
867
To initialize the Lucene fulltext search in a database, call:
868
</p>
869
<pre>
870 871 872 873 874 875 876
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>
877
<pre>
878 879 880 881 882
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>
883
PUBLIC is the schema name, TEST is the table name. The list of column names (column separated) is optional,
884
in this case all columns are indexed. The index is updated in realtime. To search the index,
885
use the following query:
886
</p>
887
<pre>
888 889 890
SELECT * FROM FTL_SEARCH('Hello', 0, 0);
</pre>
<p>
891 892
This will produce a result set that contains the query needed to retrieve the data:
</p>
893
<pre>
894
QUERY: "PUBLIC"."TEST" WHERE "ID"=1
895
</pre>
896
<p>
897 898 899 900 901 902
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
903
WHERE FT.TABLE='TEST' AND T.ID=FT.KEYS[0];</code>
904 905
</p>
<p>
906 907
You can also call the index from within a Java application:
</p>
908
<pre>
909 910
org.h2.fulltext.FullTextLucene.search(conn, text, limit, offset);
org.h2.fulltext.FullTextLucene.searchData(conn, text, limit, offset);
911 912
</pre>

Thomas Mueller's avatar
Thomas Mueller committed
913
<h2 id="user_defined_variables">User-Defined Variables</h2>
914
<p>
915
This database supports user-defined variables. Variables start with <code>@</code> and can be used wherever
916 917
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:
918
</p>
919
<pre>
920 921 922
SET @USER = 'Joe';
</pre>
<p>
923
The value can also be changed using the SET() method. This is useful in queries:
924
</p>
925
<pre>
926 927 928 929
SET @TOTAL = NULL;
SELECT X, SET(@TOTAL, IFNULL(@TOTAL, 1.) * X) F FROM SYSTEM_RANGE(1, 50);
</pre>
<p>
930
Variables that are not set evaluate to <code>NULL</code>.
931
The data type of a user-defined variable is the data type
932 933 934 935
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.
</p>

Thomas Mueller's avatar
Thomas Mueller committed
936
<h2 id="date_time">Date and Time</h2>
937 938 939
<p>
Date, time and timestamp values support ISO 8601 formatting, including time zone:
</p>
940
<pre>
941 942 943 944 945 946 947
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.
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,
948 949 950 951
you need to create a SQL script file using the <code>SCRIPT</code> command or
<code>Script</code> tool, and then load
the database using the <code>RUNSCRIPT</code> command
or the <code>RunScript</code> tool in the new time zone.
952 953
</p>

Thomas Mueller's avatar
Thomas Mueller committed
954
<h2 id="spring">Using Spring</h2>
955
<p>
956
Use the following configuration to start and stop the H2 TCP server using the Spring Framework:
957
</p>
958
<pre>
Thomas Mueller's avatar
Thomas Mueller committed
959
&lt;bean id = "org.h2.tools.Server"
960 961 962 963 964 965 966 967
            class="org.h2.tools.Server"
            factory-method="createTcpServer"
            init-method="start"
            destroy-method="stop"&gt;
    &lt;constructor-arg value="-tcp,-tcpAllowOthers,true,-tcpPort,8043" /&gt;
&lt;/bean&gt;
</pre>
<p>
968
The <code>destroy-method</code> will help prevent exceptions on hot-redeployment or when restarting the server.
969 970 971 972
</p>

<!-- [close] { --></div></td></tr></table><!-- } --><!-- analytics --></body></html>