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. [python 练习] 计算个税

    题目:利用python计算个税 说明:python有序字典的使用 代码: # -*- coding: utf-8 -*- from collections import OrderedDict # 税 ...

  2. ASP.NET页面之间传值的方式之Cookie(个人整理)

    Cookie Cookie 提供了一种在 Web 应用程序中存储用户特定信息的方法.例如,当用户访问您的站点时,您可以使用 Cookie 存储用户首选项或其他信息.当该用户再次访问您的网站时,应用程序 ...

  3. HashMap 和 Hashtable 的 6 个区别,一般人不知道最后一条

    1.线程安全 Hashtable 是线程安全的,HashMap 不是线程安全的. 为什么说 HashTable 是线程安全的? 来看下 Hashtable 的源码,Hashtable 所有的元素操作都 ...

  4. IPv4的编址方法

    重难点: 1.IP地址有3位标识符,由ICANN进行分配. 2.两级的IP地址分为 ::={<网络号>,<主机号>}. 3.在同一个局域网上的主机或路由器的IP地址中的网络号必 ...

  5. 高版本mysql8.0解压版安装步骤

    解压版安装操作官网下载: mysql-installer-community-8.0.12.0.msi如上操作: http://www.cnblogs.com/elfin/p/9429877.html ...

  6. 手机APP应用外网访问本地WEB应用

    手机APP应用外网访问本地WEB应用 本地安装了WEB服务端,手机APP应用只能在局域网内访问本地WEB,怎样使手机APP应用从公网也能访问本地WEB? 本文将介绍具体的实现步骤. 1. 准备工作 1 ...

  7. SSM项目思路整合NEW2

    上接于 https://www.cnblogs.com/shijinglu2018/p/10374541.html ...... 三)客户管理模块开发 说明:其实大致思路差不太多,都是首先根据前端页面 ...

  8. MySQL5.7 并行复制的学习

    MySQL 5.6 基于库级别的并行复制 MySQL5.6的并行复制是库(schema)级别的,从库为每个库(schema)分配一个线程以此来提高复制效率 在MySQL 5.6版本之前,Slave服务 ...

  9. pyinstaller

    下载pyinstaller pip install pyinstaller 打包文件 pyinstaller -F run.py # 打包成单个文件

  10. BZOJ-1587|前缀和 预处理 dp||叶子合并leaves

    叶子合并leaves Description 在一个美丽的秋天,丽丽每天都经过的花园小巷落满了树叶,她决定把树叶堆成K堆,小巷是笔直的 共有N片树叶(树叶排列也是笔直的),每片树叶都有一个重量值,并且 ...