springboot访问数据库(MySql)
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)的更多相关文章
- Java访问数据库Mysql
一.概述 本文主要介绍Java接连数据库的基本方法和步骤,并对其中的几个要点进行简要说明. 二.数据库访问步骤 在Java中连接数据库进行的访问主要有以下几个步骤: 加载数据库驱动 注册数据库驱动 建 ...
- Vert.x 异步访问数据库 MySQL
Vert.x提供异步访问数据库的API,数据库操作是一个耗时操作,使用传统的同步模型,容易阻塞线程,导致整体性能下降,因此我们对于数据库操作,需要使用Vert.x提供的异步API. Vert.x提供的 ...
- 使用Tomcat数据源的方式访问数据库(MySql) --Struts2框架应用与开发
1.为方便测试首先创建数据库和表,然后插入测试数据 2.打开Tomcat服务器安装目录的conf/下的context.xml,配置context.xml文件. 在<Context>标签 ...
- 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_3-1.整合Mybatis访问数据库和阿里巴巴数据源
笔记 1.整合Mybatis访问数据库和阿里巴巴数据源 简介:整合mysql 加入mybatis依赖,和加入alibaba druid数据源 1.加入依赖(可以用 http://start.s ...
- Springboot 系列(十一)使用 Mybatis(自动生成插件) 访问数据库
1. Springboot mybatis 介绍 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数获取 ...
- Holer实现外网访问本地MySQL数据库
外网访问内网MySQL数据库 内网主机上安装了MySQL数据库,只能在局域网内访问,怎样从公网也能访问本地MySQL数据库? 本文将介绍使用holer实现的具体步骤. 1. 准备工作 1.1 安装并启 ...
- 【MySql 】is not allowed to connect to this MySql server 无法访问远程MySQL数据库
问题:访问远程MySQL数据库时报错[is not allowed to connect to this MySql server ]不允许访问,因为MySQL默认只有本机localhost能够访问M ...
- 访问远程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 ...
- IntelliJ IDEA ,springboot 2.0 +mybatis 创建和访问数据库
环境: JDK8+windows10 步骤 New Module —>Spring Initializr—>next 1 2. 3.web勾选web,sql里面可以不勾,后续添加, ...
随机推荐
- springboot引入AOP
AOP是Aspect Oriented Programming的缩写,意为面向切面编程.通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术.AOP是spring框架的一个重要内容,她通过对 ...
- Nodejs使用robot操作鼠标键盘
1.安装robotjs库 前提是配置了cnpm cnpm i robotjs -g 2.如果报错VCBuild.exe,如下可以安装windows-tool MSBUILD : error MSB ...
- python练习--利用while循环和if语句,完成猜骰子的数字大小
#exampleimport random# 骰子投掷的随机叔numnum = random.randint(1,6)# 输入一个猜测的数字temp = input("请输入一个整数:&qu ...
- 03-python3.5-模拟购物车流程--更新追加细节注释功能
03-python3.5-模拟购物车流程--更新追加细节注释功能: 模拟购物车更新脚本: #!/usr/bin/env python #-*- coding: utf-8 -*- #__author_ ...
- JDK8到JDK12各个版本的重要特性整理
JDK8新特性 1.Lambda表达式 2.函数式编程 3.接口可以添加默认方法和静态方法,也就是定义不需要实现类实现的方法 4.方法引用 5.重复注解,同一个注解可以使用多次 6.引入Optiona ...
- CAN双机通讯调试小结(SJA1000与MCP2515通讯)
2011-12-07 21:36:02. 效果图: 1,51的SJA1000自收自发测试完成,见上一篇小结. 2,SJA1000自测完成后,再自测MCP2515就非常容易.主要是设置工作模式为回环模式 ...
- Django的安装和一些操作
1.安装 (1) 命令行: pip install django==1.11.18 pip install django==1.11.18 -i 源 (2) pycharm setting —> ...
- 第十三节 Ajax基础
什么是服务器:简单地,可以说服务器就是一个内存超大的计算机,可以存放很多数据和文件(当然,如果不需要太多的数据存储量,我们也可以用电脑.手机等一系列小型计算机作为服务器,只不过性能的差别而已) 网页浏 ...
- Prometheus监控学习笔记之Prometheus的Relabel,SD以及Federation功能
0x00 k8s 的监控设计 k8s 默认以及推荐的监控体系是它自己的一套东西:Heapster + cAdvisor + Influxdb + Grafana,具体可以看 这里 . 包括 k8s 自 ...
- selenium + python + nwjs
1.下载chromedriver文件 http://chromedriver.storage.googleapis.com/index.html google官方下载地址 http://dl.nwjs ...