Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

H2数据库安装与使用(单点) #24

Open
johnnian opened this issue Jul 28, 2017 · 2 comments

Comments

2 participants
@johnnian
Copy link
Owner

commented Jul 28, 2017

H2数据库是一款 Java 嵌入式数据库,之前在搭建分布式定时任务(Spring+Quartz)时,需要选择一款关系型数据库作为任务协调。H2数据库够轻量(就一个 Jar 包),使用起来还不错。

下面是具体安装使用的一些备忘:

安装部署

H2数据库版本: 1.4.196

1、下载与解压

[root@localhost ~]# wget http://www.h2database.com/h2-2017-06-10.zip
[root@localhost ~]# unzip h2-2017-06-10.zip
[root@localhost ~]# chmod +x h2/bin/*.sh
[root@localhost ~]# vi /h2/bin/h2.sh
#!/bin/sh
# 查看其他命令选项:java -cp h2*.jar org.h2.tools.Server -? 
nohup java -cp /root/h2/bin/h2*.jar org.h2.tools.Server -webAllowOthers -tcpAllowOthers -pgAllowOthers &

[root@localhost ~]# ./h2/bin/h2.sh

修改 /h2/bin/h2.sh ,改成使用 nohup 后台启动,同时设置成允许局域网其他主机连接。

启动H2后,会默认启动Web控制台(8082端口),可以通过Web控制台登录管理数据库。

h2-console

在生产环境,其实直接用命令行管理数据库更加方便;

2、创建数据库

导入脚本的方式创建数据库

[root@localhost ~]# cd /h2/bin
[root@localhost ~]# java -cp h2*.jar org.h2.tools.RunScript -url jdbc:h2:tcp://127.0.0.1/~/h2test -user sa -password 123abc -script schema_h2.sql -showResults;

上面的命令,做了下面几件事情:

  • 创建了数据库文件:~/h2test.mv.db
  • 创建账户:sa / 123abc
  • 导入SQL脚本

普通连接创建

[root@localhost ~]# cd /h2/bin
[root@localhost ~]# java -cp h2*.jar org.h2.tools.Shell -url jdbc:h2:tcp://127.0.0.1/~/test -user sa -password 123abc;

注意:

  • H2数据库,账户体系只和创建的数据库文件挂钩;
  • 连接到数据库, jdbc:h2:tcp://127.0.0.1/~/test, 如果数据库不存在,则创建一个新的;如果存在,则连接到原先的数据库;

3、数据库脚本交互

[root@localhost ~]# cd /h2/bin
[root@localhost ~]# java -cp h2*.jar org.h2.tools.Shell -url jdbc:h2:tcp://127.0.0.1/~/h2test -user sa -password 123abc;

Welcome to H2 Shell 1.4.196 (2017-06-10)
Exit with Ctrl+C
Commands are case insensitive; SQL statements end with ';'
help or ?      Display this help
list           Toggle result list / stack trace mode
maxwidth       Set maximum column width (default is 100)
autocommit     Enable or disable autocommit
history        Show the last 20 statements
quit or exit   Close the connection and exit

sql> 

4、客户端连接设置(Java:SpringBoot)

spring.datasource.url=jdbc:h2:tcp://127.0.0.1/~/h2test;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=123abc
spring.datasource.driver-class-name=org.h2.Driver

注意,连接配置的时候需要加上;DB_CLOSE_ON_EXIT=FALSE,否则,连接的客户端断开的时候,会直接关闭掉H2数据库。

5、参考

@aidway

This comment has been minimized.

Copy link

commented Mar 17, 2019

请问下文本内容自动换行是如何做的?

@johnnian

This comment has been minimized.

Copy link
Owner Author

commented Mar 18, 2019

请问下文本内容自动换行是如何做的?

在markdown格式下,普通编写的段落,都会自动换行哈~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.