-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtutorial.html
More file actions
1591 lines (1519 loc) · 64.4 KB
/
Copy pathtutorial.html
File metadata and controls
1591 lines (1519 loc) · 64.4 KB
1
2
3
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--
Copyright 2004-2025 H2 Group. Multiple-Licensed under the MPL 2.0,
and the EPL 1.0 (https://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" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>
Tutorial
</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
<!-- [search] { -->
<script type="text/javascript" src="navigation.js"></script>
</head><body onload="highlight()" onscroll="scroll()">
<table class="nav" onmousemove="return mouseMove(event)"><tr class="nav"><td class="nav" valign="top">
<div id = "searchMenu" style="width: 180px; overflow: hidden;">
<div class="menu" style="white-space:nowrap;">
<img src="images/h2-logo-2.png"
alt="H2 database logo"
onclick="document.location='main.html'"
width="136" height="74"/>
<span id = "goTop" onclick="window.scrollTo(0,0)" style="color: #fff; position:fixed; font-size: 20px; cursor: pointer;">▲</span>
</div>
<form action="submit" onsubmit="return goFirst();">
<table width="100%" class="search">
<tr class="search">
<td class="search" colspan="2">
<a href="https://translate.google.com/translate?u=https%3A%2F%2Fh2database.com"
onclick="javascript:startTranslate();return false;">Translate</a>
<div id = "translate" style="display:none"><div id = "google_translate_element"></div></div>
</td>
</tr>
<tr class="search">
<td class="search" colspan="2">
<b><label for="search">Search:</label></b>
</td>
</tr>
<tr class="search">
<td class="search" colspan="2">
<input id = "search" name="search" type="text" size="16" maxlength="100" onkeyup="listWords(this.value, '')" /><br />
<input type="reset" id = "clear" style="display:none;" value="Clear" onclick="listWords('', '');" />
</td>
</tr>
<tr class="search" style="display:none;" >
<td class="search" style="width: 1%; vertical-align: middle;">
<input id = "highlight" type="checkbox" checked="checked" onclick="highlightCurrent(this.checked, search.value)" />
</td>
<td class="search" style="width: 99%; padding: 0px; vertical-align: middle;">
<label for="highlight">Highlight keyword(s)</label>
</td>
</tr>
<tr class="search">
<td class="search" colspan="2">
<table id = "result" style="border: 0px;">
<tr style="display:none"><td></td></tr>
</table>
</td>
</tr>
</table>
</form>
<div class="menu">
<b><a href="main.html">Home</a></b><br />
<a href="download.html">Download</a><br />
<a href="cheatSheet.html">Cheat Sheet</a><br />
<br />
<b>Documentation</b><br />
<a href="quickstart.html">Quickstart</a><br />
<a href="installation.html">Installation</a><br />
<a href="tutorial.html">Tutorial</a><br />
<a href="features.html">Features</a><br />
<a href="security.html">Security</a><br />
<a href="performance.html">Performance</a><br />
<a href="advanced.html">Advanced</a><br />
<br />
<b>Reference</b><br />
<a href="commands.html">Commands</a><br />
<a href="functions.html">Functions</a><br />
• <a href="functions-aggregate.html">Aggregate</a>
• <a href="functions-window.html">Window</a>
<br /><br />
<a href="datatypes.html">Data Types</a><br />
<a href="grammar.html">SQL Grammar</a><br />
<a href="systemtables.html">System Tables</a><br />
<a href="../javadoc/index.html">Javadoc</a><br />
<a href="https://github.com/h2database/h2database/releases/download/version-2.5.250/h2.pdf">PDF (2 MB)</a><br />
<br />
<b>Support</b><br />
<a href="faq.html">FAQ</a><br />
<a href="sourceError.html">Error Analyzer</a><br />
<a href="https://groups.google.com/g/h2-database">Google Group</a><br />
<br />
<b>Appendix</b><br />
<a href="history.html">History</a><br />
<a href="license.html">License</a><br />
<a href="build.html">Build</a><br />
<a href="links.html">Links</a><br />
<a href="mvstore.html">MVStore</a><br />
<a href="architecture.html">Architecture</a><br />
<a href="migration-to-v2.html">Migration to 2.0</a><br />
<br />
</div>
</div>
</td>
<td class="nav" style="cursor: e-resize;" onmousedown="return mouseDown(event)" onmouseup="return mouseUp(event)"> </td>
<td class="nav"><div class="content">
<!-- } -->
<h1 id="tutorial_index">Tutorial</h1>
<a href="#tutorial_starting_h2_console">
Starting and Using the H2 Console</a><br />
<a href="#console_syntax">
Special H2 Console Syntax</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 />
<a href="#using_eclipselink">
Using EclipseLink</a><br />
<a href="#using_activemq">
Using Apache ActiveMQ</a><br />
<a href="#using_netbeans">
Using H2 within NetBeans</a><br />
<a href="#using_jooq">
Using H2 with jOOQ</a><br />
<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 />
<a href="#shell_tool">
The Shell Tool</a><br />
<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 />
<a href="#osgi">
OSGi</a><br />
<a href="#jmx">
Java Management Extension (JMX)</a><br />
<h2 id="tutorial_starting_h2_console">Starting and Using the H2 Console</h2>
<p>
The H2 Console application lets you access a database using a browser.
This can be a H2 database, or another database that supports the JDBC API.
</p>
<img src="images/console-2.png"
width="535" height="179"
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 H2 Console:
</p>
<table class="main">
<tr><th>OS</th><th>Start</th></tr>
<tr>
<td>Windows</td>
<td>
Click [Start], [All Programs], [H2], and [H2 Console (Command Line)]<br />
An icon will be added to the system tray:
<img src="images/db-64-t.png"
width="32" height="32"
alt="H2 database 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).
A browser window should open and point to the login page at <code class="notranslate">http://localhost:8082</code>.
</td>
</tr>
<tr>
<td>Windows</td>
<td>
Open a file browser, navigate to <code class="notranslate">h2/bin</code>, and
double click on <code class="notranslate">h2.bat</code>.<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
(URL: <code class="notranslate">http://localhost:8082</code>).
</td>
</tr>
<tr>
<td>Any</td>
<td>
Double click on the <code class="notranslate">h2*.jar</code> file.
This only works if the <code class="notranslate">.jar</code> suffix is associated with Java.
</td>
</tr>
<tr>
<td>Any</td>
<td>
Open a console window, navigate to the directory <code class="notranslate">h2/bin</code>, and type:
<pre class="notranslate">java -jar h2*.jar</pre>
</td>
</tr>
</table>
<p>
If the console startup procedure is unable to locate the default system web browser,
an error message may be displayed. It is possible to explicitly tell H2 which
program/script to use when opening a system web browser by setting either the BROWSER
environment variable, or the h2.browser java property.
</p>
<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'.
</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>
To find out which version of Java is installed, open a command prompt and type:
</p>
<pre class="notranslate">
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>
<h3>Error Message 'Port may be in use'</h3>
<p>
You can only start one instance of the H2 Console,
otherwise you will get the following error message:
"The Web server could not be started. Possible cause: another server is already running...".
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 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 class="notranslate">webPort</code>.
</p>
<p>
If no port is specified for the TCP and PG servers, each service will try to listen on its default port.
If the default port is already in use, a random port is used.
</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.
Javascript needs to be enabled.
If you started the server on the same computer as the browser, open the URL <code class="notranslate">http://localhost:8082</code>.
If you want to connect to the application from another computer, you need to provide the IP address of the server, for example:
<code class="notranslate">http://192.168.0.2:8082</code>.
If you enabled TLS on the server side, the URL needs to start with <code class="notranslate">https://</code>.
</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>
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>).
</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>
To register additional JDBC drivers (MySQL, PostgreSQL, HSQLDB,...),
add the jar file names to the environment variables <code class="notranslate">H2DRIVERS</code> or <code class="notranslate">CLASSPATH</code>.
Example (Windows): to add the HSQLDB JDBC driver
<code class="notranslate">C:\Programs\hsqldb\lib\hsqldb.jar</code>, set the environment variable
<code class="notranslate">H2DRIVERS</code> to
<code class="notranslate">C:\Programs\hsqldb\lib\hsqldb.jar</code>.
</p><p>
Multiple drivers can be set; entries need to be separated by <code class="notranslate">;</code> (Windows)
or <code class="notranslate">:</code> (other operating systems).
Spaces in the path names are supported. The settings must not be quoted.
</p>
<h3>Using the H2 Console</h3>
<p>
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.
</p>
<h3>Inserting Table Names or Column Names</h3>
<p>
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 class="notranslate">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 class="notranslate">SELECT * FROM TEST T WHERE T.</code> then the table TEST is expanded.
</p>
<h3>Disconnecting and Stopping the Application</h3>
<p>
To log out of the database, click [Disconnect] in the toolbar panel.
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].
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),
or close the console window.
</p>
<h2 id="console_syntax">Special H2 Console Syntax</h2>
<p>
The H2 Console supports a few built-in commands.
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 class="notranslate">;</code> before the command.
</p>
<table class="main">
<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 null null TEST;<br />
@tables;<br />
@tables null null TEST;<br />
</td>
<td>
Call the corresponding <code class="notranslate">DatabaseMetaData.get</code> method.
Patterns are case sensitive (usually identifiers are uppercase).
For information about the parameters, see the Javadoc documentation.
Missing parameters at the end of the line are set to null. The complete list of metadata commands is:
<code class="notranslate">
@attributes, @best_row_identifier, @catalogs, @columns,
@column_privileges, @cross_references, @exported_keys,
@imported_keys, @index_info, @primary_keys, @procedures,
@procedure_columns, @pseudo_columns, @schemas, @super_tables, @super_types,
@tables, @table_privileges, @table_types, @type_info, @udts,
@version_columns
</code>
</td>
</tr>
<tr>
<td class="notranslate">
@edit select * from test;
</td>
<td>
Use an updatable result set.
</td>
</tr>
<tr>
<td class="notranslate">
@generated insert into test() values();<br />
@generated(1) insert into test() values();<br />
@generated(ID, "TIMESTAMP") insert into test() values();
</td>
<td>
Show the result of <code class="notranslate">Statement.getGeneratedKeys()</code>.
Names or one-based indexes of required columns can be optionally specified.
</td>
</tr>
<tr>
<td class="notranslate">
@history;
</td>
<td>
List the command history.
</td>
</tr>
<tr>
<td class="notranslate">
@info;
</td>
<td>
Display the result of various <code class="notranslate">Connection</code> and <code class="notranslate">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>
Run the statement this many times.
Parameters (<code class="notranslate">?</code>) are set using a loop from 0 up to x - 1.
Random values are used for each <code class="notranslate">?/*rnd*/</code>.
A Statement object is used instead of a PreparedStatement if <code class="notranslate">@statement</code> is used.
Result sets are read until <code class="notranslate">ResultSet.next()</code> returns <code class="notranslate">false</code>.
Timing information is printed.
</td>
</tr>
<tr>
<td class="notranslate">
@maxrows 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 class="notranslate">System.gc()</code>.
</td>
</tr>
<tr>
<td class="notranslate">
@meta select 1;
</td>
<td>
List the <code class="notranslate">ResultSetMetaData</code> after running the query.
</td>
</tr>
<tr>
<td class="notranslate">
@parameter_meta select ?;
</td>
<td>
Show the result of the <code class="notranslate">PreparedStatement.getParameterMetaData()</code> calls.
The statement is not executed.
</td>
</tr>
<tr>
<td class="notranslate">
@prof_start;<br />
call hash('SHA256', '', 1000000);<br />
@prof_stop;
</td>
<td>
Start/stop the built-in profiling tool.
The top 3 stack traces of the statement(s) between start and stop are listed
(if there are 3).
</td>
</tr>
<tr>
<td class="notranslate">
@prof_start;<br />
@sleep 10;<br />
@prof_stop;
</td>
<td>
Sleep for a number of seconds. Used to profile a long running query or
operation that is running in another session (but in the same process).
</td>
</tr>
<tr>
<td class="notranslate">
@transaction_isolation;<br />
@transaction_isolation 2;
</td>
<td>
Display (without parameters) or change
(with parameters 1, 2, 4, 8) the transaction isolation level.
</td>
</tr>
</table>
<h2 id="console_settings">Settings of the H2 Console</h2>
<p>
The settings of the H2 Console are stored in a configuration file
called <code class="notranslate">.h2.server.properties</code> in you user home directory.
For Windows installations, the user home directory is usually
<code class="notranslate">C:\Documents and Settings\[username]</code> or
<code class="notranslate">C:\Users\[username]</code>.
The configuration file contains the settings of the application and is automatically created when the H2 Console is first started.
Supported settings are:
</p>
<ul><li><code class="notranslate">webAllowOthers</code>: allow other computers to connect.
</li><li><code class="notranslate">webPort</code>: the port of the H2 Console
</li><li><code class="notranslate">webSSL</code>: use encrypted TLS (HTTPS) connections.
</li><li><code class="notranslate">webAdminPassword</code>: hash of password to access preferences and tools of H2 Console,
use <code class="notranslate">org.h2.server.web.WebServer.encodeAdminPassword(String)</code> to generate a hash for your password.
Always use long complex passwords, especially when access from other hosts is enabled.
</li></ul>
<p>
In addition to those settings, the properties of the last recently used connection
are listed in the form
<code class="notranslate"><number>=<name>|<driver>|<url>|<user></code>
using the escape character <code class="notranslate">\</code>.
Example:
<code class="notranslate">1=Generic H2 (Embedded)|org.h2.Driver|jdbc\:h2\:~/test|sa</code>
</p>
<h2 id="connecting_using_jdbc">Connecting to a Database using JDBC</h2>
<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>
<pre class="notranslate">
import java.sql.*;
public class Test {
public static void main(String[] a)
throws Exception {
Connection conn = DriverManager.
getConnection("jdbc:h2:~/test", "sa", "");
// add application code here
conn.close();
}
}
</pre>
<p>
This code opens a connection (using <code class="notranslate">DriverManager.getConnection()</code>).
The driver name is <code class="notranslate">"org.h2.Driver"</code>.
The database URL always needs to start with <code class="notranslate">jdbc:h2:</code>
to be recognized by this database. The second parameter in the <code class="notranslate">getConnection()</code> call
is the user name (<code class="notranslate">sa</code> for System Administrator in this example). The third parameter is the password.
In this database, user names are not case sensitive, but passwords are.
</p>
<h2 id="creating_new_databases">Creating New Databases</h2>
<p>
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.
</p>
<p>
Auto-creation of databases can be disabled, see
<a href="features.html#database_only_if_exists">Opening a Database Only if it Already Exists</a>.
</p>
<p>
H2 Console does not allow creation of databases unless a browser window is opened by Console during its
startup or from its icon in the system tray and remote access is not enabled.
A context menu of the tray icon can also be used to create a new database.
</p>
<p>
You can also create a new local database from a command line with a Shell tool:
</p>
<pre class="notranslate">
> java -cp h2-*.jar org.h2.tools.Shell
Welcome to H2 Shell
Exit with Ctrl+C
[Enter] jdbc:h2:mem:2
URL jdbc:h2:./path/to/database
[Enter] org.h2.Driver
Driver
[Enter] sa
User your_username
Password (hidden)
Type the same password again to confirm database creation.
Password (hidden)
Connected
sql> quit
Connection closed
</pre>
<p>
By default remote creation of databases from a TCP connection or a web interface is not allowed.
It's not recommended to enable remote creation of databases due to security reasons.
User who creates a new database becomes its administrator and therefore gets the same access to your JVM as H2 has
and the same access to your operating system as Java and your system account allows.
It's recommended to create all databases locally using an embedded URL, local H2 Console, or the Shell tool.
</p>
<p>
If you really need to allow remote database creation, you can pass <code class="notranslate">-ifNotExists</code> parameter to
TCP, PG, or Web servers (but not to the Console tool).
Its combination with <code class="notranslate">-tcpAllowOthers</code>, <code class="notranslate">-pgAllowOthers</code>, or <code class="notranslate">-webAllowOthers</code>
effectively creates a remote security hole in your system, if you use it, always guard your ports with a firewall
or some other solution and use such combination of settings only in trusted networks.
</p>
<p>
H2 Servlet also supports such option.
When you use it always protect the servlet with security constraints,
see <a href="#usingH2ConsoleServlet">Using the H2 Console Servlet</a> for example;
don't forget to uncomment and adjust security configuration for your needs.
</p>
<h2 id="using_server">Using the Server</h2>
<p>
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).
Please note that only the web server supports browser connections.
The servers can be started in different ways, one is using the <code class="notranslate">Server</code> tool.
Starting the server doesn't open a database - databases are opened as soon as a client connects.
</p>
<h3>Starting the Server Tool from Command Line</h3>
<p>
To start the <code class="notranslate">Server</code> tool from the command line with the default settings, run:
</p>
<pre class="notranslate">
java -cp h2*.jar org.h2.tools.Server
</pre>
<p>
This will start the tool with the default options. To get the list of options and default values, run:
</p>
<pre class="notranslate">
java -cp h2*.jar org.h2.tools.Server -?
</pre>
<p>
There are options available to use other ports, and start or not start parts.
</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>
<li>JDBC driver class: <code class="notranslate">org.h2.Driver</code>
</li><li>Database URL: <code class="notranslate">jdbc:h2:tcp://localhost/~/test</code>
</li></ul>
<p>
For details about the database URL, see also in Features.
Please note that you can't connection with a web browser to this URL.
You can only connect using a H2 client (over JDBC).
</p>
<h3>Starting the TCP Server within an Application</h3>
<p>
Servers can also be started and stopped from within an application. Sample code:
</p>
<pre class="notranslate">
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>
The TCP server can be stopped from another process.
To stop the server from the command line, run:
</p>
<pre class="notranslate">
java org.h2.tools.Server -tcpShutdown tcp://localhost:9092 -tcpPassword password
</pre>
<p>
To stop the server from a user application, use the following code:
</p>
<pre class="notranslate">
org.h2.tools.Server.shutdownTcpServer("tcp://localhost:9092", "password", false, false);
</pre>
<p>
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.
Shutting down a TCP server is protected using the option <code class="notranslate">-tcpPassword</code>
(the same password must be used to start and stop the TCP server).
</p>
<h2 id="using_hibernate">Using Hibernate</h2>
<p>
This database supports Hibernate version 3.1 and newer. You can use the HSQLDB Dialect,
or the native H2 Dialect.
</p>
<p>
When using Hibernate, try to use the <code class="notranslate">H2Dialect</code> if possible.
When using the <code class="notranslate">H2Dialect</code>,
compatibility modes such as <code class="notranslate">MODE=MySQL</code> are not supported.
When using such a compatibility mode, use the Hibernate dialect for the
corresponding database instead of the <code class="notranslate">H2Dialect</code>;
but please note H2 does not support all features of all databases.
</p>
<h2 id="using_toplink">Using TopLink and Glassfish</h2>
<p>
To use H2 with Glassfish (or Sun AS), set the Datasource Classname to
<code class="notranslate">org.h2.jdbcx.JdbcDataSource</code>. You can set this in the GUI
at Application Server - Resources - JDBC - Connection Pools,
or by editing the file <code class="notranslate">sun-resources.xml</code>: at element
<code class="notranslate">jdbc-connection-pool</code>, set the attribute
<code class="notranslate">datasource-classname</code> to <code class="notranslate">org.h2.jdbcx.JdbcDataSource</code>.
</p>
<p>
The H2 database is compatible with HSQLDB and PostgreSQL.
To take advantage of H2 specific features, use the <code class="notranslate">H2Platform</code>.
The source code of this platform is included in H2 at
<code class="notranslate">src/tools/oracle/toplink/essentials/platform/database/DatabasePlatform.java.txt</code>.
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>
<pre class="notranslate">
<property
name="toplink.target-database"
value="oracle.toplink.essentials.platform.database.H2Platform"/>
</pre>
<p>
In old versions of Glassfish, the property name is <code class="notranslate">toplink.platform.class.name</code>.
</p>
<p>
To use H2 within Glassfish, copy the h2*.jar to the directory <code class="notranslate">glassfish/glassfish/lib</code>.
</p>
<h2 id="using_eclipselink">Using EclipseLink</h2>
<p>
To use H2 in EclipseLink, use the platform class <code class="notranslate">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="https://wiki.eclipse.org/EclipseLink/Development/Incubator/Extensions/H2Platform">H2Platform</a>.
</p>
<h2 id="using_activemq">Using Apache ActiveMQ</h2>
<p>
When using H2 as the backend database for Apache ActiveMQ, please use the <code class="notranslate">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 class="notranslate">UPDATE</code> transaction, which keeps the transaction log
from shrinking (causes the database file to grow). Instead of using an <code class="notranslate">UPDATE</code> statement, the <code class="notranslate">TransactDatabaseLocker</code> uses
<code class="notranslate">SELECT ... FOR UPDATE</code> which is not problematic.
To use it, change the ApacheMQ configuration element <code class="notranslate"><jdbcPersistenceAdapter></code> element, property
<code class="notranslate">databaseLocker="org.apache.activemq.store.jdbc.adapter.TransactDatabaseLocker"</code>.
However, using the MVCC mode will again result in the same problem. Therefore, please do not use the MVCC mode in this case.
Another (more dangerous) solution is to set <code class="notranslate">useDatabaseLock</code> to false.
</p>
<h2 id="using_netbeans">Using H2 within NetBeans</h2>
<p>
There is a known issue when using the Netbeans SQL Execution Window:
before executing a query, another query in the form <code class="notranslate">SELECT COUNT(*) FROM <query></code> is run.
This is a problem for queries that modify state, such as <code class="notranslate">SELECT NEXT VALUE FOR SEQ</code>.
In this case, two sequence values are allocated instead of just one.
</p>
<h2 id="using_jooq">Using H2 with jOOQ</h2>
<p>
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.
If this is your example schema:
</p>
<pre class="notranslate">
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 class="notranslate">
java -cp jooq.jar;jooq-meta.jar;jooq-codegen.jar;h2-1.4.199.jar;.
org.jooq.util.GenerationTool /codegen.xml
</pre>
<p>
...where <code class="notranslate">codegen.xml</code> is on the classpath and contains this information
</p>
<pre class="notranslate">
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration xmlns="http://www.jooq.org/xsd/jooq-codegen-3.11.0.xsd">
<jdbc>
<driver>org.h2.Driver</driver>
<url>jdbc:h2:~/test</url>
<user>sa</user>
<password></password>
</jdbc>
<generator>
<database>
<includes>.*</includes>
<excludes></excludes>
<inputSchema>PUBLIC</inputSchema>
</database>
<target>
<packageName>org.jooq.h2.generated</packageName>
<directory>./src</directory>
</target>
</generator>
</configuration>
</pre>
<p>
Using the generated source, you can query the database as follows:
</p>
<pre class="notranslate">
DSLContext dsl = DSL.using(connection);
Result<UserRecord> result =
dsl.selectFrom(USER)
.where(NAME.like("Johnny%"))
.orderBy(ID)
.fetch();
</pre>
<p>
See more details on <a href="https://www.jooq.org">jOOQ Homepage</a>
and in the <a href="https://www.jooq.org/tutorial">jOOQ Tutorial</a>
</p>
<h2 id="web_applications">Using Databases in Web Applications</h2>
<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
same time, you need to put the database jar in the <code class="notranslate">shared/lib</code> or
<code class="notranslate">server/lib</code> directory. It is a good idea to open the database when the
web application starts, and close it when the web application stops.
If using multiple applications, only one (any) of them needs to do
that. In the application, an idea is to use one connection per
Session, or even one connection per request (action). Those
connections should be closed after use if possible (but it's not that
bad if they don't get closed).
</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>
Add the h2*.jar file to your web application, and
add the following snippet to your web.xml file (between the
<code class="notranslate">context-param</code> and the <code class="notranslate">filter</code> section):
</p>
<pre class="notranslate">
<listener>
<listener-class>org.h2.server.web.DbStarter</listener-class>
</listener>
</pre>
<p>
If your servlet container is already Servlet 5-compatible, use the following
snippet instead:
</p>
<pre class="notranslate">
<listener>
<listener-class>org.h2.server.web.JakartaDbStarter</listener-class>
</listener>
</pre>
<p>
For details on how to access the database, see the file <code class="notranslate">DbStarter.java</code>.
By default this tool opens an embedded connection
using the database URL <code class="notranslate">jdbc:h2:~/test</code>,
user name <code class="notranslate">sa</code>, and password <code class="notranslate">sa</code>.
If you want to use this connection within your servlet, you can access as follows:
</p>
<pre class="notranslate">
Connection conn = getServletContext().getAttribute("connection");
</pre>
<p>
<code class="notranslate">DbStarter</code> can also start the TCP server, however this is disabled by default.
To enable it, use the parameter <code class="notranslate">db.tcpServer</code> in the file <code class="notranslate">web.xml</code>.
Here is the complete list of options.
These options need to be placed between the <code class="notranslate">description</code> tag
and the <code class="notranslate">listener</code> / <code class="notranslate">filter</code> tags:
</p>
<pre class="notranslate">
<context-param>
<param-name>db.url</param-name>
<param-value>jdbc:h2:~/test</param-value>
</context-param>
<context-param>
<param-name>db.user</param-name>
<param-value>sa</param-value>
</context-param>
<context-param>
<param-name>db.password</param-name>
<param-value>sa</param-value>
</context-param>
<context-param>
<param-name>db.tcpServer</param-name>
<param-value>-tcpAllowOthers</param-value>
</context-param>
</pre>
<p>
When the web application is stopped, the database connection will be closed automatically.
If the TCP server is started within the <code class="notranslate">DbStarter</code>, it will also be stopped automatically.
</p>
<h3 id="usingH2ConsoleServlet">Using the H2 Console Servlet</h3>
<p>
The H2 Console is a standalone application and includes its own web server, but it can be
used as a servlet as well. To do that, include the <code class="notranslate">h2*.jar</code> file in your application, and
add the following configuration to your <code class="notranslate">web.xml</code>:
</p>
<pre class="notranslate">
<servlet>
<servlet-name>H2Console</servlet-name>
<servlet-class>org.h2.server.web.WebServlet</servlet-class>
<!--
<init-param>
<param-name>webAllowOthers</param-name>
<param-value></param-value>
</init-param>
<init-param>
<param-name>trace</param-name>
<param-value></param-value>
</init-param>
-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>H2Console</servlet-name>
<url-pattern>/console/*</url-pattern>
</servlet-mapping>
<!--
<security-role>
<role-name>admin</role-name>
</security-role>
<security-constraint>
<web-resource-collection>
<web-resource-name>H2 Console</web-resource-name>
<url-pattern>/console/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
-->
</pre>
<p>
For details, see also <code class="notranslate">src/tools/WEB-INF/web.xml</code>.
</p>
<p>
If your application is already Servlet 5-compatible, use the servlet class
<code class="notranslate">org.h2.server.web.JakartaWebServlet</code> instead.
</p>
<p>
To create a web application with just the H2 Console, run the following command:
</p>
<pre class="notranslate">
build warConsole
</pre>
<h2 id="csv">CSV (Comma Separated Values) Support</h2>
<p>
The CSV file support can be used inside the database using the functions
<code class="notranslate">CSVREAD</code> and <code class="notranslate">CSVWRITE</code>,
or it can be used outside the database as a standalone tool.
</p>