咱們知道,JDBC是JDK自帶的接口規範,不一樣的數據庫有不一樣的實現,只須要引入相應的驅動包便可。html
在使用MySQL數據庫時,引入的是MySQL驅動,相應的,使用H2數據庫時,也須要引入H2驅動包:java
<dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <!-- <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> -->
在SpringBoot的application.properties文件配置相應屬性:mysql
spring.datasource.driver-class-name=org.h2.Driver spring.datasource.url=jdbc:h2:~/folder spring.datasource.username=root spring.datasource.password=123456
JDBC URL的做用能夠決定H2是用內存仍是磁盤文件存儲數據等,詳細介紹以下:spring
鏈接語法([] 可選,<>可變):sql
jdbc:h2:[file:][<path>]<databaseName>
例如:數據庫
jdbc:h2:~/test //鏈接位於用戶目錄下的test數據庫 jdbc:h2:file:/data/sample jdbc:h2:file:E:/H2/gacl //只在Windows下使用
在Window操做系統下,"~"這個符號表明的就是當前登陸到操做系統的用戶對應的用戶目錄,好比我當前是使用Administrator用戶登陸操做系統的,因此在"C:\Documents and Settings\Administrator.h2"目錄中就能夠找到test數據庫對應的數據庫文件了。app
鏈接語法:tcp
jdbc:h2:mem:<databasename>
示例:url
jdbc:h2:mem:test_mem
這種鏈接方式就和其餘數據庫相似了,是基於Service的形式進行鏈接的,所以容許多個客戶端同時鏈接到H2數據庫。操作系統
鏈接語法:
jdbc:h2:tcp://<server>[:<port>]/[<path>]<databaseName>
範例:
jdbc:h2:tcp://localhost/~/test //用戶目錄下 jdbc:h2:tcp://localhost/E:/H2/gacl //指定目錄 jdbc:h2:tcp://localhost/mem:gacl //內存數據庫
而後,就能夠像使用MySQL同樣的使用H2了。