使用JDBC 获取相关的数据

什么是JDBC

Java Database Connectivity 是一种用于执行SQL语句的Java API,与数据库建立连接、发送 操作数据库的语句并处理结果。

Spring Boot 使用 JDBC

增加依赖

  • 修改pom.xml:将dependecies 修改为如下两个
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>

创建 Customer.java 类

package com.example.kane.Model;

public class Customer {
private long id;
private String firstName, lastName; public Customer(long id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
} @Override
public String toString() {
return String.format(
"Customer[id=%d, firstName='%s', lastName='%s']",
id, firstName, lastName);
} // getters & setters omitted for brevity
}

修改Application 类

package com.example.kane;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling; import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate; import com.example.kane.Model.Customer; @SpringBootApplication
//@EnableScheduling
public class RestfulWebService1Application implements CommandLineRunner{ private static final Logger log = LoggerFactory.getLogger(RestfulWebService1Application.class); public static void main(String args[]) {
SpringApplication.run(RestfulWebService1Application.class, args);
} @Autowired
JdbcTemplate jdbcTemplate; @Override
public void run(String... strings) throws Exception { log.info("Creating tables"); jdbcTemplate.execute("DROP TABLE customers IF EXISTS");
jdbcTemplate.execute("CREATE TABLE customers(" +
"id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))"); // Split up the array of whole names into an array of first/last names
List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream()
.map(name -> name.split(" "))
.collect(Collectors.toList()); // Use a Java 8 stream to print out each tuple of the list
splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1]))); // Uses JdbcTemplate's batchUpdate operation to bulk load data
jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)", splitUpNames); log.info("Querying for customer records where first_name = 'Josh':");
jdbcTemplate.query(
"SELECT id, first_name, last_name FROM customers WHERE first_name = ?", new Object[] { "Josh" },
(rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))
).forEach(customer -> log.info(customer.toString()));
}
}

运行项目看结果

2019-03-01 14:19:52.078  INFO 7436 --- [  restartedMain] c.e.kane.RestfulWebService1Application   : Creating tables
2019-03-01 14:19:52.086 INFO 7436 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2019-03-01 14:19:52.392 INFO 7436 --- [ restartedMain] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2019-03-01 14:19:52.429 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Inserting customer record for John Woo
2019-03-01 14:19:52.430 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Inserting customer record for Jeff Dean
2019-03-01 14:19:52.430 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Inserting customer record for Josh Bloch
2019-03-01 14:19:52.430 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Inserting customer record for Josh Long
2019-03-01 14:19:52.461 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Querying for customer records where first_name = 'Josh':
2019-03-01 14:19:52.480 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Customer[id=3, firstName='Josh', lastName='Bloch']
2019-03-01 14:19:52.480 INFO 7436 --- [ restartedMain] c.e.kane.RestfulWebService1Application : Customer[id=4, firstName='Josh', lastName='Long']
2019-03-01 14:20:01.122 INFO 7436 --- [nio-8080-exec-5] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-03-01 14:20:01.123 INFO 7436 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2019-03-01 14:20:01.146 INFO 7436 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet : Completed initialization in 22 ms

说明

官网的例子,没有配置JDBC Template的Datasource,默认使用的是H2 的内存存储的数据库,只能当做测试使用。下面会有介绍更改DataSource的方法

介绍下 CommandLineRunner

功能

在项目启动后,执行执行功能,我们可以定一个类,去实现CommandLineRunner接口,重写run方法,执行一部分操作。需要注意的是,定义类必须标记为Spring管理的组件

测试类

package com.example.kane.Model;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(value=1) //因为可能有许多事情要做,Order 可以根据大小,判读执行的顺序
public class run_after_application implements CommandLineRunner{ @Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println("-----------------------");
} }

介绍下JdbcTempalte

在JDBC核心包中,JdbcTemplate是主要的类,简化了JDBC的使用,避免了一些常规错误。它能够执行JDBC核心流程,在应用代码之上提供SQL语句、导出结果。这个类执行SQL查询、更新、对结果集重复操作捕获JDBC的异常。并将它翻译成org.springframework.dao 包中定义的基本的、信息量更大的异常层次结构。

JDBC构造方法

  • JdbcTemplate()
//为Bean创建一个JdbcTemplate以供使用
//再没配置DataSource的情况下 springboot提供了 一些嵌入式的数据库支持,上面的例子使用的就是H2数据库,是一个内存的数据库
  • JdbcTemplate(javax.sql.DataSource dataSource)
//构造的时候传入一个 DataSource,来获取链接
//JdbcTemplate Spring boot默认链接的是H2 database,

在spring boot中配置mysql 数据库

  • 数据库配置类 db_config
package com.example.kane.config;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class db_config {
//这个类是一个Config类
@Value("${db.driver}")
private String DRIVER; @Value("${db.password}")
private String PASSWORD; @Value("${db.url}")
private String URL; @Value("${db.username}")
private String USERNAME;
@Bean
public DataSource dataSource1() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(DRIVER);
dataSource.setUrl(URL);
dataSource.setUsername(USERNAME);
dataSource.setPassword(PASSWORD);
return dataSource;
}
}
  • application.properties
# Database
# mysqljdbc连接驱动
db.driver:com.mysql.cj.jdbc.Driver
db.url:jdbc:mysql://localhost:3306/test
db.username:root
db.password:root
  • pom.xml
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 需要用到commons-dbcp连接池,以及连接mysql使用的drver-->
  • application 启动类修改
    @Autowired
JdbcTemplate jdbcTemplate;
//下面是加载了数据库的配置。只需要增加这个
@Autowired
db_config db_config;
  • 运行程序后会发现数据存储到本地数据库
SELECT * from customers;
------------------------
1 John Woo
2 Jeff Dean
3 Josh Bloch
4 Josh Long

另一个简单的方法配置mysql数据库

  • 直接修改application.properties
# database
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  • 将properties改成yml文件 application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver

注:这两种方式又回归到配置文件的方式了,

JDBC Template常用方法

关于连接池的一些内容

  • 为什么要使用数据库连接池?

    因为建立数据库连接是一个非常耗时的过程,使用连接池可以预先同数据库建立连接,放在内存中。应用需要使用数据库的时候直接使用连接池中的连接即可。

  • 当前三大主流连接池

    • DBCP:提供最大空闲连接数,超过连接全部自动断开连接,其他两个没有。
    • C3P0:提供最大空闲连接时间,这样可以做到自动收回空闲连接的机制
    • Druid:阿里出品的,同样提供最大的空闲连接时间

【Spring Boot】使用JDBC 获取相关的数据的更多相关文章

  1. Spring Boot 整合JDBC 实现后端项目开发

    一.前言 二.新建Spring Boot 项目 三.Spring Boot 整合JDBC 与MySQL 交互 3.1 新建数据表skr_user 3.2 Jdbcproject 项目结构如下 3.3 ...

  2. Spring Boot系列(三) Spring Boot 之 JDBC

    数据源 类型 javax.sql.DataSource javax.sql.XADataSource org.springframework.jdbc.datasource.embedded,Enbe ...

  3. spring boot: @Entity @Repository一个简单的数据读存储读取

    spring boot: @Entity @Repository一个简单的数据读存储读取 创建了一个实体类. 如何持久化呢?1.使用@Entity进行实体类的持久化操作,当JPA检测到我们的实体类当中 ...

  4. spring boot: 用thymeleaf嵌套循环展示多层数据(spring boot 2.3.2)

    一,什么情况下会用到嵌套循环? 当我们展示多个分类时,每个分类下又展示出推荐的前几个商品,   这时我们需要用到嵌套循环 看一个例子: 说明:刘宏缔的架构森林是一个专注架构的博客,地址:https:/ ...

  5. spring boot+mybaits+mysql+generato(逆向工程)+前后台数据交互

    如按照我博客上没有弄出来 请在下面留言 我好修改 谢谢 小弟使用的是Eclipse 首先下载STS插件 help--->Elipse Marketplace--->find搜索栏里面搜索S ...

  6. Spring Boot 基础概述与相关约定配置

    今天打算整理一下 Spring Boot 的基础篇,这系列的文章是我业余时间来写的,起源于之前对微服务比较感兴趣,微服务的范畴比较广包括服务治理.负载均衡.断路器.配置中心.API网关等,还需要结合 ...

  7. SpringBoot 源码解析 (三)----- Spring Boot 精髓:启动时初始化数据

    在我们用 springboot 搭建项目的时候,有时候会碰到在项目启动时初始化一些操作的需求 ,针对这种需求 spring boot为我们提供了以下几种方案供我们选择: ApplicationRunn ...

  8. Spring Boot使用JDBC方式连接MySQL

    首先去spring官网下载一个名为test的Spring Boot项目模板:https://start.spring.io/ 然后在mysql中的testdb数据库中新建一张名为test_user的表 ...

  9. 78. Spring Boot完美使用FastJson解析JSON数据【从零开始学Spring Boot】

    [原创文章,转载请注明出处] 个人使用比较习惯的json框架是fastjson,所以spring boot默认的json使用起来就很陌生了,所以很自然我就想我能不能使用fastjson进行json解析 ...

随机推荐

  1. 创建表空间、新增用户、给用户赋予DBA权限 、删除用户下的上有数据表

    正文原创 一:查询数据库实例有多少用户: [oracle@localhost ~]$ sqlplus / as sysdba; SQL*Plus: Release 11.2.0.3.0 Product ...

  2. VM_Centos7.3_X64_安装Oracle12C 总结笔记

    声明:本文居多内容参考原文来之网络: 一:安装Centos7.3 虚拟机 1:操作系统下载 CentOS 7官方下载地址:https://www.centos.org/download/ 说明:本案例 ...

  3. 基于vue-cli3的vue项目移动端样式适配,lib-flexible和postcss-px2rem

    1,安装 flexible和 postcss-px2rem(命令行安装) npm install lib-flexible --save npm install postcss-px2rem --sa ...

  4. 【Linux】安装多个JDK并切换

    一.JDK安装1.将安装包jdk-8u111-linux-x64.tar.gz拷贝到安装目录(如/usr/java)下.2.添加可执行权限chmod +x jdk-8u111-linux-x64.ta ...

  5. Socket网络编程(二)

    udp协议发送消息案例 1.创建UdpServer(udp服务器端) package com.cppdy.udp; import java.net.DatagramPacket; import jav ...

  6. GIL锁

    GIL锁                                                                           在CPython中,这个全局解释器锁,也称 ...

  7. Memcached常用语法与java连接服务

    memcached常用语法及java使用方式 Author:SimpleWu Memcached 存储命令 Memcached set 命令用于将 value(数据值) 存储在指定的 key(键) 中 ...

  8. cf1143E 倍增好题!

    一开始感觉用莫队可以搞一下,但是看了题解才发现这题其实是倍增套路题 把排列转换成nxt数组,然后倍增dp[i][j]表示第i个数后面有(1<<j)个数的最靠左的区间 然后从右往左扫一次即可 ...

  9. CF1015F

    玄学字符串dp... 题意:给定一个括号序列,求长度为2n的合法的括号序列的个数(要求每个被统计的合法序列中均至少有一个子串为给定的括号序列) 题解: 这题没有想的那么复杂,就是暴力的一个dp 首先我 ...

  10. 通过自定义比较器排序(C#版)

    一.方法概述 自定义比较器需要实现接口IComparer<T> 二.示例过程 1.新建一个Product产品类 /// <summary> /// 产品类 /// </s ...