tutorial.html 22.5 KB
Newer Older
1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2
<!-- 
3
Copyright 2004-2007 H2 Group. Licensed under the H2 License, Version 1.0 (http://h2database.com/html/license.html). 
4 5
Initial Developer: H2 Group
-->
6 7
<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>
8
Tutorial
9
</title><link rel="stylesheet" type="text/css" href="stylesheet.css" />
10 11 12 13 14 15
<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">
16
    Starting and Using the H2 Console</a><br />
17
<a href="#connecting_using_jdbc">
18
    Connecting to a Database using JDBC</a><br />
19
<a href="#creating_new_databases">
20
    Creating New Databases</a><br />
21
<a href="#using_server">
22
    Using the Server</a><br />    
23
<a href="#using_hibernate">
24
    Using Hibernate</a><br />
25
<a href="#web_applications">
26
    Using Databases in Web Applications</a><br />
27
<a href="#csv">
28
    CSV (Comma Separated Values) Support</a><br />
29
<a href="#upgrade_backup_restore">
30
    Upgrade, Backup, and Restore</a><br />
31
<a href="#open_office">
32
    Using OpenOffice Base</a><br />
33
<a href="#web_start">
34
    Java Web Start / JNLP</a><br />
35 36
<a href="#fulltext">
    Fulltext Search</a><br />
37

38
<br /><a name="tutorial_starting_h2_console"></a>
39
<h2>Starting and Using the H2 Console</h2>
40
<p>
41 42
This application lets you access a SQL database using a browser interface.
This can be a H2 database, or another database that supports the JDBC API.
43
</p>
44
<img src="images/console.png" alt="Web Browser - H2 Console Server - H2 Database" />
45
<p>
46
This is a client / server application, so both a server and a client (a browser) are required to run it.
47
</p><p>
48
Depending on your platform and environment, there are multiple ways to start the application:
49
</p>
50
<table><tr><th>OS</th><th>Start</th></tr>
51 52 53
<tr>
  <td>Windows</td>
  <td>
54 55 56
    Click [Start], [All Programs], [H2], and [H2 Console (Command Line)]<br />
    When using the Sun JDK 1.4 or 1.5, a window with the title 'H2 Console ' should appear.
    When using the Sun JDK 1.6, an icon will be added to the system tray:
57
    <img src="images/h2.png" alt="[H2 icon]" /><br />
58 59
    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).
60
    A browser window should open and point to the Login page http://localhost:8082).
61 62 63 64 65
  </td>
</tr>
<tr>
  <td>Windows</td>
  <td>
66 67 68
    Open a file browser, navigate to h2/bin, and double click on h2.bat.<br />
    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 
69
    (URL: http://localhost:8082).
70 71 72 73 74
  </td>
</tr>
<tr>
  <td>Any</td>
  <td>
75
      Open a console window, navigate to the directory 'h2/bin' and type:
76 77 78 79 80 81 82 83
<pre>
java -cp h2.jar org.h2.tools.Server
</pre>
  </td>
</tr>
</table>

<h3>Firewall</h3>
84
<p>
85
If you start the server, you may get a security warning from the firewall (if you have installed one).
86
If you don't want other computers in the network to access the application on your machine, you can
87 88 89
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.
90
</p><p>
91 92
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'.
93
</p>
94 95

<h3>Native Version</h3>
96
<p>
97 98 99
The native version does not require Java, because it is compiled using GCJ.
However H2 does currently not run stable with GCJ on Windows
It is possible to compile the software to different platforms. 
100
</p>
101 102

<h3>Testing Java</h3>
103
<p>
104 105 106 107 108
To check the Java version you have installed, open a command prompt and type:
<pre>
java -version
</pre>
If you get an error message, you may need to add the Java binary directory to the path environment variable.
109
</p>
110 111

<h3>Error Message 'Port is in use'</h3>
112
<p>
113 114 115 116 117
You can only start one instance of the H2 Console, 
otherwise you will get the following error message:
<code>Port is in use, maybe another ... server already running on...</code>.
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.
118
</p>
119 120

<h3>Using another Port</h3>
121
<p>
122 123 124 125
If the port is in use by another application, you may want to start the H2 Console on a different port.
This can be done by changing the port in the file .h2.server.properties. This file is stored
in the user directory (for Windows, this is usually in "Documents and Settings/&lt;username&gt;").
The relevant entry is webPort.
126
</p>
127 128

<h3>Starting Successfully</h3>
129
<p>
130 131 132 133 134 135 136
If starting the server from a console window was successful, 
a new window will open and display the following text:
<pre>
H2 Server running on port 9092
Webserver running on https://localhost:8082/
</pre>
Don't click inside this window; otherwise you might block the application (if you have the Fast-Edit mode enabled).
137
</p>
138 139

<h3>Connecting to the Server using a Browser</h3>
140
<p>
141 142 143 144 145
If the server started successfully, you can connect to it using a web browser.
The browser needs to support JavaScript, frames and cascading stylesheets (css).
If you started the server on the same computer as the browser, go to http://localhost:8082 in the browser.
If you want to connect to the application from another computer, you need to provide the IP address of the server, for example:
http://192.168.0.2:8082. If you enabled SSL on the server side, the URL needs to start with HTTPS.
146
</p>
147 148

<h3>Multiple Concurrent Sessions</h3>
149
<p>
150 151
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.
152
</p>
153 154

<h3>Application Properties</h3>
155
<p>
156 157 158
Starting the server will create a configuration file in you local home directory called <code>.h2.server.properties</code>.
For Windows installations, this file will be in the directory <code>C:\Documents and Settings\[username]</code>.
This file contains the settings of the application.
159
</p>
160 161

<h3>Login</h3>
162
<p>
163 164 165
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].
166
</p><p>
167 168
You can save and reuse previously saved settings. The settings are stored in the 
Application Properties file.
169
</p>
170 171

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

<h3>Adding Database Drivers</h3>
178
<p>
179 180 181
Additional database drivers can be registered by adding the Jar file location of the driver to the environment
variables H2DRIVERS or CLASSPATH. Example (Windows): To add the database driver library 
C:\Programs\hsqldb\lib\hsqldb.jar, set the environment variable H2DRIVERS to 
182 183
C:\Programs\hsqldb\lib\hsqldb.jar.
</p><p>
184 185
Multiple drivers can be set; each entry needs to be separated with a ';' (Windows) or ':' (other operating systems).
Spaces in the path names are supported. The settings must not be quoted.
186
</p><p>
187
Only the Java version supports additional drivers (this feature is not supported by the Native version).
188
</p>
189 190

<h3>Using the Application</h3>
191
<p>
192 193 194
The application has three main panels, the toolbar on top, the tree on the left and the query / result panel on the right.
The database objects (for example, tables) are listed on the left panel.
Type in a SQL command on the query panel and click 'Run'. The result of the command appears just below the command.
195
</p>
196 197

<h3>Inserting Table Names or Column Names</h3>
198
<p>
199 200 201 202
The table name and column names can be inserted in the script by clicking them in the tree.
If you click on a table while the query is empty, a 'SELECT * FROM ...' is added as well.
While typing a query, the table that was used is automatically expanded in the tree.
For, example if you type 'SELECT * FROM TEST T WHERE T.' then the table TEST is automatically expanded in the tree.
203
</p>
204 205

<h3>Disconnecting and Stopping the Application</h3>
206
<p>
207
On the browser, click 'Disconnect' on the toolbar panel. You will be logged out of the database.
208 209
However, the server is still running and ready to accept new sessions.
</p><p>
210 211 212 213
To stop the server, right click on the system tray icon and select [Exit]. 
If you don't have the icon (because you started it in another way), 
press [Ctrl]+[C] on the console where the server was started (Windows),
or close the console window.
214
</p>
215

216
<br /><a name="connecting_using_jdbc"></a>
217
<h2>Connecting to a Database using JDBC</h2>
218
<p>
219 220 221 222 223 224 225 226 227
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:
<pre>
import java.sql.*;
public class Test {
  public static void main(String[] a) 
  throws Exception {
    Class.forName("org.h2.Driver");
    Connection conn = DriverManager.
228
      getConnection("jdbc:h2:~/test", "sa", ""); 
229 230 231 232 233 234 235 236 237 238 239
    // add application code here
  }
}
</pre>
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> in every case.
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 ('sa' for System Administrator in this example). The third parameter is the password.
Please note that in this database, user names are not case sensitive, but passwords are case sensitive.
240
</p>
241

242
<br /><a name="creating_new_databases"></a>
243
<h2>Creating New Databases</h2>
244
<p>
245
By default, if the database specified in the URL does not yet exist, a new (empty) 
246 247
database is created automatically. The user that created the database automatically becomes
the administrator of this database.
248
</p>
249

250
<br /><a name="using_server"></a>
251
<h2>Using the Server</h2>
252
<p>
253 254
H2 currently supports three servers: a Web Server, a TCP Server and an ODBC Server.
The servers can be started in different ways.
255
</p>
256

257
<h3>Starting the Server from Command Line</h3>
258
<p>
259 260 261 262
To start the Server from the command line with the default settings, run
<pre>
java org.h2.tools.Server
</pre>
263
This will start the Server with the default options. To get the list of options and default values, run
264 265 266 267 268
<pre>
java org.h2.tools.Server -?
</pre>
There are options available to use a different ports, and start or not start 
parts of the Server and so on. For details, see the API documentation of the Server tool.
269
</p>
270

271
<h3>Connecting to the TCP Server</h3>
272
<p>
273
To remotly connect to a database using the TCP server, use the following driver and database URL:
274
</p>
275 276 277 278
<ul>
<li>JDBC driver class: org.h2.Driver
</li><li>Database URL: jdbc:h2:tcp://localhost/~/test
</li></ul>
279
<p>
280
For details about the database URL, see also in Features.
281
</p>
282 283

<h3>Starting the Server within an Application</h3>
284
<p>
285 286 287 288
It is also possible to start and stop a Server from within an application. Sample code:
<pre>
import org.h2.tools.Server;
...
289
// start the TCP Server
290
Server server = Server.createTcpServer(args).start();
291 292 293 294
...
// stop the TCP Server
server.stop();
</pre>
295
</p>
296 297

<h3>Stopping a TCP Server from Another Process</h3>
298
<p>
299 300 301 302 303 304 305 306 307 308 309 310 311
The TCP Server can be stopped from another process. 
To stop the server from the command line, run:
<pre>
java org.h2.tools.Server -tcpShutdown tcp://localhost:9092
</pre>
To stop the server from a user application, use the following code:
<pre>
org.h2.tools.Server.shutdownTcpServer("tcp://localhost:9094");
</pre>
This function will call System.exit on the server.
This function should be called after all connection to the databases are closed 
to avoid recovery when the databases are opened the next time.
To stop remote server, remote connections must be enabled on the server.
312
</p>
313

314
<h3>Limitations of the Server</h3>
315
<p>
316
There currently are a few limitations when using the server or cluster mode:
317
</p>
318 319 320 321 322 323
<ul>
<li>Statement.cancel() is only supported in embedded mode.
    A connection can only execute one operation at a time in server or cluster mode,
    and is blocked until this operation is finished.
</li></ul>

324
<br /><a name="using_hibernate"></a>
325
<h2>Using Hibernate</h2>
326
<p>
327 328
This database supports Hibernate version 3.1 and newer. You can use the HSQLDB Dialect, 
or the native H2 Dialect that is available in the file src/tools/org/h2/tools/hibernate/H2Dialect.txt.
329
The H2 dialect is included in newer version of Hibernate. For versions where the dialect is missing, you need to copy the file
330
into the folder src\org\hibernate\dialect (Hibernate 3.1), rename it to H2Dialect.java and re-compile hibernate.
331
</p>
332

333
<br /><a name="web_applications"></a>
334
<h2>Using Databases in Web Applications</h2>
335
<p>
336 337
There are multiple ways to access a database from within web
applications. Here are some examples if you use Tomcat or JBoss.
338
</p>
339 340

<h3>Embedded Mode</h3>
341
<p>
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
The (currently) most simple solution is to use the database in the
embedded mode, that means open a connection in your application when
it starts (a good solution is using a Servlet Listener, see below), or
when a session starts. A database can be accessed from multiple
sessions and applications at the same time, as long as they run in the
same process. Most Servlet Containers (for example Tomcat) are just
using one process, so this is not a problem (unless you run Tomcat in
clustered mode). Tomcat uses multiple threads and multiple
classloaders. If multiple applications access the same database at the
same time, you need to put the database jar in the shared/lib or
server/lib directory. It is a good idea to open the database when the
web application starts, and close it when the web applications 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).
359
</p>
360 361

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

<h3>Using a Servlet Listener to Start and Stop a Database</h3>
367
<p>
368 369
Add the h2.jar file your web application, and
add the following snippet to your web.xml file (after context-param and before filter):
370 371
<pre>
&lt;listener>
372
   &lt;listener-class>org.h2.server.web.DbStarter&lt;/listener-class>
373 374
&lt;/listener>
</pre>
375
For details on how to access the database, see the code DbStarter.java
376
</p>
377

378
<br /><a name="csv"></a>
379
<h2>CSV (Comma Separated Values) Support</h2>
380
<p>
381 382
The CSV file support can be used inside the database using the functions CSVREAD and CSVWRITE, 
and the CSV library can be used outside the database as a standalone tool.
383
</p>
384 385

<h3>Writing a CSV File from Within a Database</h3>
386
<p>
387 388 389 390 391 392 393
The built-in function CSVWRITE can be used to create a CSV file from a query.
Example:
<pre>
CREATE TABLE TEST(ID INT, NAME VARCHAR);
INSERT INTO TEST VALUES(1, 'Hello'), (2, 'World');
CALL CSVWRITE('test.csv', 'SELECT * FROM TEST');
</pre>
394
</p>
395 396

<h3>Reading a CSV File from Within a Database</h3>
397
<p>
398 399 400 401
A CSV file can be read using the function CSVREAD. Example:
<pre>
SELECT * FROM CSVREAD('test.csv');
</pre>
402
</p>
403 404

<h3>Writing a CSV File from a Java Application</h3>
405
<p>
406 407 408 409 410 411 412
The CSV tool can be used in a Java application even when not using a database at all.
Example:
<pre>
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("NAME", Types.VARCHAR, 255, 0);
rs.addColumn("EMAIL", Types.VARCHAR, 255, 0);
rs.addColumn("PHONE", Types.VARCHAR, 255, 0);
413 414
rs.addRow(new String[]{"Bob Meier", "bob.meier@abcde.abc", "+41123456789"});
rs.addRow(new String[]{"John Jones", "john.jones@abcde.abc", "+41976543210"});
415 416
Csv.write("test.csv", rs, null);
</pre>
417
</p>
418 419

<h3>Reading a CSV File from a Java Application</h3>
420
<p>
421 422 423 424 425 426 427 428 429 430 431 432 433
It is possible to read a CSV file without opening a database.
Example:
<pre>
ResultSet rs = Csv.read("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();
</pre>
434
</p>
435

436
<br /><a name="upgrade_backup_restore"></a>
437 438 439
<h2>Upgrade, Backup, and Restore</h2>

<h3>Database Upgrade</h3>
440
<p>
441 442 443
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.
444
</p>
445

446
<h3>Backup using the Script Tool</h3>
447
<p>
448 449 450
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. 
451
This can be done using the Script tool:
452
<pre>
453
java org.h2.tools.Script -url jdbc:h2:~/test -user sa -script test.zip -options compression zip
454
</pre>
455
It is also possible to use the SQL command SCRIPT to create the backup of the database.
456 457 458
For more information about the options, see the SQL command SCRIPT.
The backup can be done remotely, however the file will be created on the server side.
The built in FTP server could be used to retrieve the file from the server.
459
</p>
460

461
<h3>Restore from a Script</h3>
462
<p>
463 464
To restore a database from a SQL script file, you can use the RunScript tool:
<pre>
465
java org.h2.tools.RunScript -url jdbc:h2:~/test -user sa -script test.zip -options compression zip
466 467 468 469 470 471 472 473
</pre>
For more information about the options, see the SQL command RUNSCRIPT.
The restore can be done remotely, however the file needs to be on the server side.
The built in FTP server could be used to copy the file to the server.
It is also possible to use the SQL command RUNSCRIPT to execute a SQL script.
SQL script files may contain references to other script files, in the form of
RUNSCRIPT commands. However, when using the server mode, the references script files
need to be available on the server side.
474
</p>
475

476
<h3>Online Backup</h3>
477
<p>
478 479 480 481 482 483 484 485 486 487
The BACKUP SQL statement and the Backup tool both create a zip file 
with all database files. However, the contents of this file are not human readable. 
Other than the SCRIPT statement, the BACKUP statement does not lock the
database objects, and therefore does not block other users. The resulting
backup is transactionally consistent:
<pre>
BACKUP TO 'backup.zip'
</pre>
The Backup tool (org.h2.tools.Backup) can not be used to create a online backup;
the database must not be in use while running this program.
488
</p>
489

490
<br /><a name="open_office"></a>
491
<h2>Using OpenOffice Base</h2>
492
<p>
493 494 495
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:
496
</p>
497 498
<ul>
<li>Stop OpenOffice, including the autostart
499 500 501 502 503 504
</li><li>Copy h2.jar into the directory &lt;OpenOffice&gt;\program\classes
</li><li>Start OpenOffice Base
</li><li>Connect to an existing database, select JDBC, [Next]
</li><li>Example datasource URL: jdbc:h2:c:/temp/test
</li><li>JDBC driver class: org.h2.Driver
</li></ul>
505
<p>
506
Now you can access the database stored in the directory C:/temp.
507
</p>
508 509 510

<br /><a name="web_start"></a>
<h2>Java Web Start / JNLP</h2>
511
<p>
512 513 514 515 516 517
When using Java Web Start / JNLP (Java Network Launch Protocol), permissions tags must be set in the .jnlp file, 
and the application .jar file must be signed. Otherwise, when trying to write to the file system, the following 
exception will occur: java.security.AccessControlException: access denied (java.io.FilePermission ... read).
Example permission tags:
<pre>
&lt;security>
518
    &lt;all-permissions/>
519 520
&lt;/security>
</pre>
521
</p>
522

523 524 525 526 527 528 529 530 531
<br /><a name="fulltext"></a>
<h2>Fulltext Search</h2>
<p>
H2 supports Lucene full text search and native full text search implementation. 
</p>

<h3>Using the Native Full Text Search</h3>
<p>
To initialize, call:
532
</p>
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
<pre>
CREATE ALIAS IF NOT EXISTS FT_INIT FOR "org.h2.fulltext.FullText.init";
CALL FT_INIT();
</pre>
<p>
Afterwards, you can create a full text index for a table using:
</p>
<pre>
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>
PUBLIC is the schema, TEST is the table name. The list of column names (column separated) is optional, 
in this case all columns are indexed. The index is updated in read time. 
To search the index, use the following query:
</p>
<pre>
SELECT * FROM FT_SEARCH('Hello', 0, 0);
</pre>
<p>
You can also call the index from within a Java application:
</p>
<pre>
org.h2.fulltext.FullText.search(conn, text, limit, offset)
</pre>

<h3>Using the Lucene Fulltext Search</h3>
<p>
To use the Lucene full text search, you first need to rename the file FullTextLucene.java.txt to FullTestLucene.java and compile it. Also, you need the Lucene library in the classpath.
To initialize, call:
</p>
<pre>
CREATE ALIAS IF NOT EXISTS FTL_INIT FOR "org.h2.fulltext.FullTextLucene.init";
CALL FTL_INIT();
</pre>
<p>
Afterwards, you can create a full text index for a table using:
</p>
<pre>
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>
PUBLIC is the schema, TEST is the table name. The list of column names (column separated) is optional, 
in this case all columns are indexed. The index is updated in read time. To search the index, use the following query:
</p>
<pre>
SELECT * FROM FTL_SEARCH('Hello', 0, 0);
</pre>
<p>
You can also call the index from within a Java application:
</p>
<pre>
org.h2.fulltext.FullTextLucene.search(conn, text, limit, offset)
</pre>

591
</div></td></tr></table></body></html>