1.使用JDBC访问数据库:JDBC是用于在Java语言编程中与数据库连接的API

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

2.数据源配置

dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>

3.配置数据库

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

4.新建接口

/**
* user的service
*/
public interface IUserService {
/**
*
* @param name
* @param age
*/
int create(String name,Integer age); /**
* 根据用户名删除用户
* @param name
*/
void deleteByName(String name); /**
* 获取用户总数
* @return
*/
Integer getUsersCount(); /**
* 删除所有用户
*/
void deleteAllUsers();
}

5.实现接口

@Service
public class UserServiceImpl implements IUserService {
@Autowired
private JdbcTemplate jdbcTemplate;//Spring的JdbcTemplate是自动配置的,可直接使用
@Override
public int create(String name, Integer age) {
int flag = jdbcTemplate.update("insert into USER(NAME, AGE) values(?, ?)", name, age);
return flag;
} @Override
public void deleteByName(String name) {
jdbcTemplate.update("delete from USER where NAME = ?", name);
} @Override
public Integer getUsersCount() {
return jdbcTemplate.queryForObject("select count(1) from USER", Integer.class);
} @Override
public void deleteAllUsers() {
jdbcTemplate.update("delete from USER");
}
}

6.测试代码

 /**
* 测试数据库连接
*/
@Autowired
private IUserService userSerivce; @Test
public void testJdbc() throws Exception {
// 插入5个用户
int flag = userSerivce.create("a", 1);
System.out.println(flag);
userSerivce.create("b", 2);
userSerivce.create("c", 3);
userSerivce.create("d", 4);
userSerivce.create("e", 5); // 查数据库,应该有5个用户
Assert.assertEquals(5, userSerivce.getUsersCount().intValue()); // 删除两个用户
userSerivce.deleteByName("a");
userSerivce.deleteByName("e"); // 查数据库,应该有5个用户
Assert.assertEquals(3, userSerivce.getUsersCount().intValue()); }

7.多数据源配置

(1) 创建一个Spring配置类,定义两个DataSource用来读取application.properties中的不同配置

/**
* 多数据源配置
*/ @Configuration
public class DataSourceConfig { @Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
} @Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@Primary
@ConfigurationProperties(prefix="spring.datasource1")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
} //将多数据源注入JdbcTemplate
@Bean(name = "primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(
@Qualifier("primaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
} @Bean(name = "secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(
@Qualifier("secondaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
} }

(2)配置文件

#单数据源时spring.datasource.url是可以的,多数据源时要写成spring.datasource.jdbc-url
#网上这样说,在2.0升级之后需要变更成:spring.datasource.jdbc-url和spring.datasource.driver-class-name即可解决!
spring.datasource.jdbc-url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource1.jdbc-url=jdbc:mysql://localhost:3306/test1
spring.datasource1.username=root
spring.datasource1.password=123456
spring.datasource1.driver-class-name=com.mysql.jdbc.Driver

(3)测试

/***
* 多数据源
*/
@Autowired
@Qualifier("primaryJdbcTemplate")
protected JdbcTemplate jdbcTemplate1; @Autowired
@Qualifier("secondaryJdbcTemplate")
protected JdbcTemplate jdbcTemplate2; @Test
public void test3() throws Exception { // 往第一个数据源中插入两条数据
jdbcTemplate1.update("insert into user(name,age) values( ?, ?)", "aaa", 20);
jdbcTemplate1.update("insert into user(name,age) values( ?, ?)", "bbb", 30); // 往第二个数据源中插入一条数据,若插入的是第一个数据源,则会主键冲突报错
jdbcTemplate2.update("insert into user(id,name,age) values(?,?, ?)", 5,"aaa", 20);
}v

springboot访问数据库(MySql)的更多相关文章

  1. Java访问数据库Mysql

    一.概述 本文主要介绍Java接连数据库的基本方法和步骤,并对其中的几个要点进行简要说明. 二.数据库访问步骤 在Java中连接数据库进行的访问主要有以下几个步骤: 加载数据库驱动 注册数据库驱动 建 ...

  2. Vert.x 异步访问数据库 MySQL

    Vert.x提供异步访问数据库的API,数据库操作是一个耗时操作,使用传统的同步模型,容易阻塞线程,导致整体性能下降,因此我们对于数据库操作,需要使用Vert.x提供的异步API. Vert.x提供的 ...

  3. 使用Tomcat数据源的方式访问数据库(MySql) --Struts2框架应用与开发

    1.为方便测试首先创建数据库和表,然后插入测试数据   2.打开Tomcat服务器安装目录的conf/下的context.xml,配置context.xml文件. 在<Context>标签 ...

  4. 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_3-1.整合Mybatis访问数据库和阿里巴巴数据源

    笔记 1.整合Mybatis访问数据库和阿里巴巴数据源     简介:整合mysql 加入mybatis依赖,和加入alibaba druid数据源 1.加入依赖(可以用 http://start.s ...

  5. Springboot 系列(十一)使用 Mybatis(自动生成插件) 访问数据库

    1. Springboot mybatis 介绍 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数获取 ...

  6. Holer实现外网访问本地MySQL数据库

    外网访问内网MySQL数据库 内网主机上安装了MySQL数据库,只能在局域网内访问,怎样从公网也能访问本地MySQL数据库? 本文将介绍使用holer实现的具体步骤. 1. 准备工作 1.1 安装并启 ...

  7. 【MySql 】is not allowed to connect to this MySql server 无法访问远程MySQL数据库

    问题:访问远程MySQL数据库时报错[is not allowed to connect to this MySql server ]不允许访问,因为MySQL默认只有本机localhost能够访问M ...

  8. 访问远程mysql数据库,出现报错,显示“1130 - Host'xxx.xxx.xxx.xxx' is not allowed to connect to this MySQL server“

    在使用Navicat for MySQl访问远程mysql数据库,出现报错,显示“1130 - Host'xxx.xxx.xxx.xxx' is not allowed to connect to t ...

  9. IntelliJ IDEA ,springboot 2.0 +mybatis 创建和访问数据库

    环境: JDK8+windows10 步骤 New Module —>Spring Initializr—>next 1 ​ 2. ​ 3.web勾选web,sql里面可以不勾,后续添加, ...

随机推荐

  1. Leetcode: Number Complement

    Given a positive integer, output its complement number. The complement strategy is to flip the bits ...

  2. Go 初体验 - 闭包的几种情况

    闭包: 闭包是可以包含自由(未绑定到特定对象)变量的代码块,这些变量不在这个代码块内或者任何全局上下文中定义,而是在定义代码块的环境中定义.要执行的代码块(由于自由变量包含在代码块中,所以这些自由变量 ...

  3. python模块学习之hashlib模块学习

    # 加密模块 import hashlib # md5 加密 md5 # 1.初始化md5模块 生成md5对象 # 2.引入要加密的数据 update # 3.获取加密值 hexdigest m = ...

  4. P1772 [ZJOI2006]物流运输

    题目描述 物流公司要把一批货物从码头A运到码头B.由于货物量比较大,需要n天才能运完.货物运输过程中一般要转停好几个码头.物流公司通常会设计一条固定的运输路线,以便对整个运输过程实施严格的管理和跟踪. ...

  5. Class打包成jar

    Class打包成jar 现在我的文件夹的目录在: C:\Users\linsenq\Desktop\cglibjar 我要把位于这个目录下的所有文件夹以及这个文件夹下的.class文件打成jar包 第 ...

  6. mysql的group_concat列转行函数

    SELECT auditor,sum(count) total, GROUP_CONCAT(type,'=', count) AS type_count FROM auditor_dm_ol GROU ...

  7. CentOS7开放端口号

    查看所有开放的端口号 firewall-cmd --zone=public --list-ports 或者 firewall-cmd --permanent --list-ports(--perman ...

  8. my work

    Dad, what's your first job? How did you achieved?

  9. Vue 组件&组件之间的通信 之 非父子关系组件之间的通信

    Vue中不同的组件,即使不存在父子关系也可以相互通信,我们称为非父子关系通信: 我们需要借助一个空Vue实例,在不同的组件中,使用相同的Vue实例来发送/监听事件,达到数据通信的目的: 实例: 初始加 ...

  10. Linux 启动时profile、bashrc、~/.bash_profile、~/.bashrc、~/.bash_profile执行顺序以及文件说明

    Linux 启动时profile.bashrc.~/.bash_profile.~/.bashrc.~/.bash_profile执行顺序以及文件说明 一.执行顺序 登录linux时,/etc/pro ...