H2数据库

H2数据库

之如何查看内存数据库H2中的数据

H2是常用的开源数据库之一,其他还有Derby,HSQLDB,MySQL,PostgreSQL。其中H2,HSQLDB类似,十分适合作为嵌入式数据库使用,其它的数据库大部分都需要安装独立的客户端和服务器端。

H2的优势:

1、h2采用纯Java编写,因此不受平台的限制。

2、h2只有一个jar文件,十分适合作为嵌入式数据库使用。

3、性能和功能的优势

工具/原料

  • springboot
  • h2

创建H2数据库文件

1.进入H2工具(在阿里云盘里有)的安装目录
2.执行命令 java -cp h2-{版本号}.jar org.h2.tools.Shell
3.输入 url 即jdbc:h2:~/{数据库名称}
4.选择驱动,直接回车,默认驱动就好
5.输入即将创建的 demo 库的管理员用户名,笔者设为 root
6.输入即将创建的 demo 库的管理员密码,笔者设为 admin123456
7.再次确认管理员密码 admin123456
8.输入quit or exit退出

方法/步骤

在pom文件中增加H2的依赖

<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
    <scope>runtime</scope>
</dependency>

在pom中增加spring-devtools依赖,并且一定要是web项目

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
	<optional>true<optional>
</dependency>

在application.yml中增加数据库的配置,spring.datasource.url为数据库连接地址

spring:
  h2:
    console:
      settings:
        web-allow-others: true
      path: /h2-console
      enabled: ${zfile.debug} # debuge模式才会开启h2提供的web交互功能
  datasource:
    # h2 内存数据库 配置
    driver-class-name: org.h2.Driver
    url: jdbc:h2:数据库文件路径
    username: username
    password: pwd

增加初始化脚本,放在resources路径下,在springboot项目启动时会自动执行脚本,初始化数据

启动项目,在浏览器中访问路径/h2-console,出现如下页面

如何查看内存数据库H2中的数据

输入正确的JDBC URL,用户名和密码,默认没有密码,JDBC URL是你配置文件中的路径,点击连接,即可看到如下页面

如何查看内存数据库H2中的数据

在右侧输入sql语句,即可查询数据库中的数据。

springboot 项目中对H2数据库增删改查

引入依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

通过jdbctemolate操作

@Autowired
private JdbcTemplate jdbcTemplate;

H2数据库的操作语法与mysql类似

参考

文章:
https://jingyan.baidu.com/article/0a52e3f4fc53aabf62ed72b5.html
H2创建数据库文件:https://blog.csdn.net/sinat_41811051/article/details/124431873
项目:
https://github.com/zhaojun1998/zfile

posted @ 2022-04-12 22:36  黄河大道东  阅读(2028)  评论(0编辑  收藏  举报