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. AMBER: CPPTRAJ Tutorial C0

    CPPTRAJ作为PTRAJ的继任者,拥有比PTRAJ更强大的功能,本教程会简要的介绍CPPTRAJ的用法及注意事项. 需要的文件: trpzip2.gb.nc trpzip2.ff10.mbondi ...

  2. chrome浏览器多开的方法

    Chrome浏览器在上网的过程中,会保存一些用户数据,如缓存.cookie.收藏的网页等信息. 这些信息的保存位置是可以设置的.方法也很简单: 桌面上复制一个Chrome的快捷方式,编辑属性,添加-- ...

  3. 解决IE浏览器把application/json响应视为文件并尝试下载

    下面我的解决方案是针对.net MVC的,其他的解决方案也类似,就是把响应的mimeType换成IE浏览器已经拥有的.如application/json换成text/plain #region 退出登 ...

  4. windows----------telnet不是内部命令问题

    1.

  5. href和src的区别(小计)

    1.Src 是指向物件的来源地址,请求src资源时会将其指向的资源下载并应用文档中 src的内容是页面上比不可少的一部分,是引入.在 img.script.iframe 等元素上使用. 2.href ...

  6. VS2008生成解决方案卡顿、龟速

    1.工具-选项-项目和解决方案-MS BUILD 项目生成输出详细信息中选择“诊断” 2.进入.NET环境的安装位置:C:\WINDOWS\Microsoft.NET\Framework\v3.5 , ...

  7. (简单)华为M3揽月 BTV-W09的Usb调试模式在哪里开启的经验

    每次我们使用pc链上安卓手机的时候,如果手机没有开启Usb调试模式,pc则没办法成功识别我们的手机,有时候,我们使用的一些功能较好的app如以前我们使用的一个app引号精灵,老版本就需要开启Usb调试 ...

  8. 标签EL和JSTL解读

    1. EL标签:出现代替输出:<%=%> EL输出格式(特点:只能输出,不带逻辑)  ${key值} 查找顺序:page,request,session,application **在不加 ...

  9. 0x16 Tire

    参考链接:https://www.cnblogs.com/TheRoadToTheGold/p/6290732.html 题目链接:https://www.acwing.com/problem/con ...

  10. js备战春招の四のDOM

    通过js查找html元素的三种方法: 1.通过id找到html元素. 2.通过标签名找到html元素. 3.通过类名找到html元素. DOM HTML document.write(); 直接写入h ...