JDBC与Springboot相遇


1、JDBC

先上个我的JDBC模版:

import java.sql.*;

public class TestDB {
    public static final String url = "jdbc:mysql://localhost:3306/db_student?useSSL=false";
    private static final  String user = "root";
    private static final  String pass = "root";
    public static void main(String args[]) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("......MySQL load failed!");
        }
        try {
            System.out.println(".....MySQL load sucessfully! ");
            System.out.println(".....Connecting to MySQL...............");
            Connection connect = DriverManager.getConnection(url, user, pass);
            System.out.println(".....Creating statement..............");
            Statement stmt = connect.createStatement();
            ResultSet rs=null;

            String sql2;
            sql2 = "create table workshop" +
                    "(id integer not null," +
                    "place varchar(10))";
            stmt.executeUpdate(sql2);// 数据库建表

            String sql3;//向数据库插入数据
            sql3 = "insert into test_db.workshop " + "values(5,'pku')";
            stmt.executeUpdate(sql3);

            String sql4;//数据库修改
            String modify="BUT";
            sql4="update workshop "+
            "set place='"+modify+"' where id=4";
            stmt.executeUpdate(sql4);

            String sql5;//数据库删除数据
            sql5="delete from workshop where id=5";
            stmt.executeUpdate(sql5);

            String sql1;// 查询语句
            sql1 = "select * from test_db.workshop";
            rs = stmt.executeQuery(sql1);
            while (rs.next()) {
                System.out.println("ID:" + rs.getInt("id") + '\t' + "place:" + rs.getString("place"));
            }
            String sql6;//where条件查询
            sql6="select * from workshop where id>2";
            rs=stmt.executeQuery(sql6);
            while(rs.next()){
                System.out.println("ID:"+rs.getInt("id")+'\t'+"place:"+rs.getString("place"));
            }
            connect.close();
            stmt.close();
            rs.close();
            System.out.println(".............Mission Successed!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(".............MySql connecte failed");
        }
    }
}

在原始java代码中,既要自己写连接,又要自己选择是预编译sql还是sql语句,当接入web之后,还要抓取request对象之内的;虽然搞清逻辑之后还是比较简单,但是在我看了Springboot框架中的MySQL支持和Springboot中的jdbc之后————封装之后居然这么简单!!!!!

2、Springboot整合JDBC

2.1、IDEA添加mysql支持

务必加上JDBC API接口和MySQL Dirver,否则程序无法运行!!!

这样一来,聪明的Springboot会自动为我们配置好pom.xml文件:

<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>

2.2、在哪儿存放数据库连接账号?

Springboot项目创建好了之后,会自动生成application.proproites文件,这个文件可以放一些配置,通过源码可以发现,Springboot底层扫包时还会扫描以.yml的文件(同级目录下)。相比之下我更喜欢.yml文件。

配置yml(yaml一样)文件:

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/db_student
    driver-class-name: com.mysql.jdbc.Driver

连接数据库之后,在DataSource加上一个@Autowired注解,Spring会自动装配成这个个DataSource对象,相当于它被加载到了IOC容器中,之后直接从里面取值就行了。

2.3、测试一下

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class DataApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
        //查看一下默认的数据源
        System.out.println(dataSource.getClass());
        //获得数据库连接
        Connection connection= dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }

}

Connection connection= dataSource.getConnection();便完成连接,然而这只是一种方法!!!

O(∩_∩)O哈哈~还封装了另外一个对象!!!

2.4、JdbcTemplate

Springboot中还有一个JdbcTemplate对象,这个玩意儿怎么说喃?我感觉更nb一点

直接上一个例子:

String sql="select * from t_course";
List list=jdbcTemplate.queryForList(sql);

如果你要查询全部信息,两句话就完了!!!相比之下,比之前那个简单了不知道多少。将信息存入LIst即可

来看个完整的:

package com.fatzard.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
public class jdbcController {

    @Autowired
    JdbcTemplate jdbcTemplate;

    //查询数据库的所有信息
    //没有实体类,获取数据库的东西------用map
    @RequestMapping("/userlist")
    public List<Map<String,Object>>userList(){
        String sql="select * from t_course";
        return jdbcTemplate.queryForList(sql);
    }

    @RequestMapping(value="/addUser/{a}/{b}/{c}")
    public String addUser(@PathVariable String a,@PathVariable String b,@PathVariable String c){
        String sql="insert into db_student.t_user(N_USER_ID,VC_LOGIN_NAME,VC_PASSWORD) values("+a+",'"+b+"','"+c+"')";
        System.out.println(sql);
        jdbcTemplate.update(sql);
        return "OK";
    }
}

你看还可以直接和前端进行请求,前端传入请求,直接就可以处理;利用restful风格的url地址还可以直接通过url地址请求就完成数据库的更新,相同地,什么数据库增删改查,稍微改一下就可以了!


文章作者: fatzard
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 fatzard !
评论
  目录
本站总访问量