在springboot极简教程001-开始也提到了,比较推荐使用MySQL的分支版本MariaDB来进行学习,很多线上的生产环境都在使用,所以学习阶段就可以开始熟悉它。直接网上搜索MariaDB下载安装即可。
-- 创建utf8mb4字符集的数据库test
create database test default character set utf8mb4;
-- 修改表score的字符集为utf8
alter table score default character set utf8;
mysql -uroot -proot
service mysqld restart
mysql>source d:/student.sql
mysql> show variables like '%storage_engine%';
DROP DATABASE IF EXISTS student;
CREATE DATABASE student DEFAULT CHARACTER SET utf8;
参考后面的**【测试用数据库表及SQL】**
show databases;
show create table user;
ALTER TABLE user ENGINE=INNODB;
如果要更改整个数据库表的存储引擎,一般要一个表一个表的修改,比较繁琐,可以采用先把数据库导出,得到SQL,把MyISAM全部替换为INNODB,再导入数据库的方式。
转换完毕后重启mysql。
student.sql:
DROP DATABASE IF EXISTS student;
CREATE DATABASE student DEFAULT CHARACTER SET utf8;
use student;
CREATE TABLE student(
id int(11) NOT NULL AUTO_INCREMENT,
student_id int(11) NOT NULL UNIQUE,
name varchar(255) NOT NULL,
age int(11) NOT NULL,
sex varchar(255) NOT NULL,
birthday date DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
insert into student(student_id, name, age, sex, birthday) value(2018001, "Alice", 28, "女", "1990-10-18");
insert into student(student_id, name, age, sex, birthday) value(2018002, "Bob", 27, "男", "1991-10-18");
insert into student(student_id, name, age, sex, birthday) value(2018003, "David", 26, "男", "1992-10-18");
insert into student(student_id, name, age, sex, birthday) value(2018004, "Jim", 38, "男", "1980-10-18");
insert into student(student_id, name, age, sex, birthday) value(2018005, "Mark", 18, "男", "2000-10-18");
在springboot中如果要使用MySQL,需要添加依赖:
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.21version>
dependency>
然后需要配置数据源,在application.yml中添加配置:
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/student?characterEncoding=UTF-8
password: "root"
username: "root"
测试数据源是否正确,可以在单元测试中添加测试:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyspringbootApplication.class)
public class TestDataSource {
@Autowired
private ApplicationContext applicationContext;
@Test
public void test(){
DataSource dataSource = applicationContext.getBean(DataSource.class);
System.out.println(dataSource);
}
}
一般数据源连接出问题大多是application.yml配置有误,需要仔细检查下,例如我就遇到过这样的错误:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
原因是spring.datasource.url配置的数据库不对,要改为自己创建的数据库名;或者是数据库不存在,需要手动创建一下。