一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - SpringBoot使用JDBC獲取相關(guān)的數(shù)據(jù)方法

SpringBoot使用JDBC獲取相關(guān)的數(shù)據(jù)方法

2021-07-18 16:04WangKane Java教程

這篇文章主要介紹了SpringBoot使用JDBC獲取相關(guān)的數(shù)據(jù)方法,JDBC與數(shù)據(jù)庫建立連接、發(fā)送 操作數(shù)據(jù)庫的語句并處理結(jié)果,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

什么是jdbc

java database connectivity 是一種用于執(zhí)行sql語句的java api,與數(shù)據(jù)庫建立連接、發(fā)送 操作數(shù)據(jù)庫的語句并處理結(jié)果。

spring boot 使用 jdbc

增加依賴

修改pom.xml:將dependecies 修改為如下兩個

?
1
2
3
4
5
6
7
8
9
10
<dependencies>
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-jdbc</artifactid>
    </dependency>
    <dependency>
      <groupid>com.h2database</groupid>
      <artifactid>h2</artifactid>
    </dependency>
  </dependencies>

創(chuàng)建 customer.java 類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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 類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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()));
  }
}

運(yùn)行項目看結(jié)果

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

說明

官網(wǎng)的例子,沒有配置jdbc template的datasource,默認(rèn)使用的是h2 的內(nèi)存存儲的數(shù)據(jù)庫,只能當(dāng)做測試使用。下面會有介紹更改datasource的方法

介紹下 commandlinerunner

功能

在項目啟動后,執(zhí)行執(zhí)行功能,我們可以定一個類,去實現(xiàn)commandlinerunner接口,重寫run方法,執(zhí)行一部分操作。 需要注意的是,定義類必須標(biāo)記為spring管理的組件

測試類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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 可以根據(jù)大小,判讀執(zhí)行的順序
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的使用,避免了一些常規(guī)錯誤。它能夠執(zhí)行jdbc核心流程,在應(yīng)用代碼之上提供sql語句、導(dǎo)出結(jié)果。這個類執(zhí)行sql查詢、更新、對結(jié)果集重復(fù)操作捕獲jdbc的異常。并將它翻譯成 org.springframework.dao 包中定義的基本的、信息量更大的異常層次結(jié)構(gòu)。

jdbc構(gòu)造方法

jdbctemplate()

?
1
2
//為bean創(chuàng)建一個jdbctemplate以供使用
//再沒配置datasource的情況下 springboot提供了 一些嵌入式的數(shù)據(jù)庫支持,上面的例子使用的就是h2數(shù)據(jù)庫,是一個內(nèi)存的數(shù)據(jù)庫

jdbctemplate(javax.sql.datasource datasource)

?
1
2
//構(gòu)造的時候傳入一個 datasource,來獲取鏈接
//jdbctemplate spring boot默認(rèn)鏈接的是h2 database,

在spring boot中配置mysql 數(shù)據(jù)庫

數(shù)據(jù)庫配置類 db_config

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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

?
1
2
3
4
5
6
# database
# mysqljdbc連接驅(qū)動
db.driver:com.mysql.cj.jdbc.driver
db.url:jdbc:mysql://localhost:3306/test
db.username:root
db.password:root

pom.xml

?
1
2
3
4
5
6
7
8
9
10
11
<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 啟動類修改

?
1
2
3
4
5
@autowired
  jdbctemplate jdbctemplate;
  //下面是加載了數(shù)據(jù)庫的配置。只需要增加這個
  @autowired
  db_config db_config;

運(yùn)行程序后會發(fā)現(xiàn)數(shù)據(jù)存儲到本地數(shù)據(jù)庫

?
1
2
3
4
5
6
select * from customers;
------------------------
1  john  woo
2  jeff  dean
3  josh  bloch
4  josh  long

另一個簡單的方法配置mysql數(shù)據(jù)庫

直接修改application.properties

?
1
2
3
4
5
# 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

?
1
2
3
4
5
6
spring:
 datasource:
  url: jdbc:mysql://localhost:3306/test
  username: root
  password: root
  driver-class-name: com.mysql.cj.jdbc.driver

注:這兩種方式又回歸到配置文件的方式了,

jdbc template常用方法

  • execute方法: 可以用于執(zhí)行任何sql語句,一般用于執(zhí)行ddl語句;
  • update方法及batchupdate方法: update方法用于執(zhí)行新增、修改、刪除等語句;batchupdate方法用于執(zhí)行批處理相關(guān)語句;
  • query方法及queryforxxx方法: 用于執(zhí)行查詢相關(guān)語句;
  • call方法: 用于執(zhí)行存儲過程、函數(shù)相關(guān)語句。

參考官網(wǎng) https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/jdbctemplate.html

關(guān)于連接池的一些內(nèi)容

為什么要使用數(shù)據(jù)庫連接池?

因為建立數(shù)據(jù)庫連接是一個非常耗時的過程,使用連接池可以預(yù)先同數(shù)據(jù)庫建立連接,放在內(nèi)存中。應(yīng)用需要使用數(shù)據(jù)庫的時候直接使用連接池中的連接即可。

當(dāng)前三大主流連接池

  • dbcp:提供最大空閑連接數(shù),超過連接全部自動斷開連接,其他兩個沒有。
  • c3p0:提供最大空閑連接時間,這樣可以做到自動收回空閑連接的機(jī)制
  • druid:阿里出品的,同樣提供最大的空閑連接時間

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:http://www.cnblogs.com/primadonna/p/10470472.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 日本人与黑人做爰视频网站 | 好大好硬好深好爽想要吃奶 | 精品精品国产自在香蕉网 | 99久热只有精品视频免费观看17 | 欧美大陆日韩一区二区三区 | 欧美亚洲一区二区三区在线 | 满溢游泳池免费 | jizzjizz大学生| 高跟丝袜麻麻求我调教 | 日本亚洲免费 | 久久国产精品免费网站 | 日本性生活免费看 | 深夜激情网站 | www日本视频 | 日本四虎影院 | 欧美亚洲天堂网 | 国产精品久久久久影视不卡 | 欧美日韩成人在线视频 | 扒开大腿狠狠挺进视频 | seetube18日本第一次 | 70岁多老妇人特黄a级毛片 | 亚洲欧美日韩另类在线一 | 亚洲 日韩 在线 国产 视频 | 青草久久伊人 | 欧美成人tv | 国产一及毛片 | 成年人在线免费观看视频网站 | xxxxx性13一14 | 亚洲天堂网2018 | 免费一级毛片在线播放 | 精品国产成人 | 暖暖影院日本版 | 男女小视频在线观看 | 欧美日韩亚洲成人 | 日日爽| 色天天久久| 日韩免费在线视频 | 99国产精品热久久久久久夜夜嗨 | 97久久天天综合色天天综合色hd | piss美女厕所小便 | 四虎影视永久免费视频观看 |