springboot手动配置数据库

11 篇文章 2 订阅
10 篇文章 0 订阅

springboot有多种连接数据库的方式,包括JDBC、JPA、MyBatis、多数据源和事务。本文使用JDBC连接数据库。

  • 1、引入数据库的依赖oracle/mysql

<!-- 数据库 -->
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>10.2.0.2.0</version>
</dependency>
<!-- jdbc -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- 数据库 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<!-- jdbc -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
  • 2、application.properties上增加数据库的配置

注:由于springboot会自动读取数据库驱动jar包中的META-INF/services/java.sql.Driver文件,文件中的值就是数据源的driverClassName的值,所以,配置数据源时,无须配置driverClassName

###################oracle##########################
spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
spring.datasource.username=root
spring.datasource.password=root
###################mysql##########################
#spring.datasource.url=jdbc:mysql://localhost:3306/newdb?useUnicode=true&characterEncoding=utf8
#spring.datasource.username=root
#spring.datasource.password=root
  • 3、进行单元测试

package com.springboot.example.example;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class ExampleApplicationTests {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Test
    public void contextLoads() {
        String sql = "select * from student where id=1";
        System.out.println(jdbcTemplate.queryForMap(sql));
    }

}
  • 4、打印结果:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值