環境 idea2019.2 jdk1.8 數據庫mysql 5.7
項目 結構
new ->Project 使用springboot快速搭建web項目 選好sdk next
填寫項目信息 next
點Web-->勾選 Spring Web
點SQL->勾選 JDBC API 和 MySQL Driver
確認最后的項目信息 Finish 篇幅太長 點開看 這個例子只是生成了表 最后的例子中有數據生成
創建下面兩個配置文件 放在resource目錄下

spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/jdbc?useSSL=true&serverTimezone=UTC&characterEncoding=UTF8 data-username: root data-password: root initialization-mode: always schema=classpath: schema.sql

DROP TABLE IF EXISTS `department`; CREATE TABLE `department` ( `id` int(11) NOT NULL AUTO_INCREMENT, `departmentName` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
手動新建jdbc數據庫 測試數據庫連接
@RunWith(SpringRunner.class)手動添加 沒有自動生成
@RunWith(SpringRunner.class) @SpringBootTest class Springboot06jdbcApplicationTests { @Autowired DataSource dataSource; @Test void contextLoads() throws SQLException { System.out.println("------>>>"+dataSource.getClass()); Connection connection = dataSource.getConnection(); System.out.println("=========>>>"+connection); connection.close(); } }
springboot 2 以后默認使用HikariDataSource 數據源
使用Hikari連接池
驗證后 運行spingboot啟動類即可
結果
如果想生成表 並生成數據 請看下面操作
user.sql
drop table if exists user; create table user (id bigint(20) not null auto_increment, username varchar(40) DEFAULT NULL, name varchar(20) DEFAULT NULL, age int(3) DEFAULT NULL, balance decimal(10,2) DEFAULT NULL, primary key(id))ENGINE=InnoDB DEFAULT CHARSET=utf8;
data.sql
insert into user (id, username, name, age, balance) values (1,'account1','張三', 20, 100.00); insert into user (id, username, name, age, balance) values (2,'account2','李四', 28, 180.00); insert into user (id, username, name, age, balance) values (3,'account3','王五', 32, 280.00);
修改application.yml
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/jdbc?useSSL=true&serverTimezone=UTC&characterEncoding=UTF8 data-username: root data-password: root initialization-mode: always #schema=classpath: schema.sql schema=classpath: user.sql data=classpath: data.sql
生成表並且插入數據
完整的項目結構