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里面可以不勾,后续添加, ...
随机推荐
- Cocos Creator (webgl模式下怎么让canvas背景透明)
项目中构建出web-mobile包后,打开main.js 在main.js中加入如下两行即可让canvas变透明 cc.director.setClearColor(new cc.Color(0,0, ...
- HDFS组件性能调优:数据平衡
生产系统中什么情况下会添加一个节点呢? 1 增加存储能力 disk 2 增加计算能力 cpu mem 如果增加是的是存储能力,说明存储已接近饱和或者说过段时间就会没有剩余的空间给作业来用.新加的节点存 ...
- World is Exploding (容斥 + 统计)
题意:满足题目中的式子,a < b && c < d && Va < Vb && Vc > Vd 思路:先求不讨论位置重合的情况 ...
- CSS制作渐变背景色
<style type="text/css"> #grad1 { background: -webkit-linear-gradient(#C2F2F0,#); /* ...
- Linux串口通信之termios结构体说明
termios结构体中,该结构体一般包括如下的成员:tcflag_t c_iflag; tcflag_t c_oflag; tcflag_t c_cflag; tcfla ...
- WdatePicker 日期区间设置
<input id="billsStartDate" name="billsStartDate" onclick="WdatePicker({d ...
- 第01节:ActiveMQ入门和消息中间件
1.ActiveMQ最主要的功能:实现JMS Provider,用来帮助实现高可用.高性能.可伸缩.易用和安全的企业级面向消息服务的系统.是一个异步的功能. 2.ActiveMQ特点: 完全支持JMS ...
- MySQL ERROR 1698 (28000): Access denied for user 'root'@'localhost'
今天在安装MySQL的过程中竟然没有让我输入密码,登录的时候也不需要密码就能进入,这让我很困惑. 进了数据库就设置密码,用了各种方式都不行. 虽然我这数据库没啥东西但也不能没有密码就裸奔啊,有点丢人是 ...
- ACTIVEMQ 实例化到MSSQL
实例化文章很多,不重复,自行查询 直接上XML <!-- Licensed to the Apache Software Foundation (ASF) under one or more c ...
- 对八皇后的补充以及自己解决2n皇后问题代码
有了上次的八皇后的基础.这次准备解决2n皇后的问题,: //问题描述// 给定一个n*n的棋盘,棋盘中有一些位置不能放皇后.现在要向棋盘中放入n个黑皇后和n个白皇后,使任意的两个黑皇后都不在同一行./ ...