Spring Data 01 :JDBC 访问 MySQL

目录

Spring Data 01 :JDBC 访问 MySQL

Spring Data 02 :Spring JdbcTemplate 访问 MySQL

Spring Data 03 :JPA入门

Spring Data 04:Spring Data JPA入门

Spring Data 05 : Spring Data JPA + SpringBoot2 集成多数据源


一、添加依赖:jdbc的mysql连接驱动

    
      mysql
      mysql-connector-java
      8.0.15
    

    
      junit
      junit
      4.11
      test
    
  

二、添加JDBCUtil工具类:获取Connection,关闭Connection、Statement、ResultSet

package com.springboot.utils;
/**
 * author: x
 * Date:6/21/2019 11:03 AM
 */

import java.io.IOException;
import java.sql.*;


public class JDBCUtil {

    /**
     * @Description 获取Connection
     * @Return 所获得的JDBC的Connection
     * 工具类一般都是静态的,当其被使用时,直接通过类名.方法直接获取,不需要创建
     * */
    public static Connection getConnection() throws ClassNotFoundException, SQLException, IOException {
        String url = "jdbc:mysql://localhost:3306/student";
        String user = "root";
        String password = "root";
        String driverClass = "com.mysql.jdbc.Driver";

        Class.forName(driverClass);
        Connection connection = DriverManager.getConnection(url,user,password);
        return connection;
    }

    /**
     * 释放DB相关的资源
      */
    public static void release(ResultSet resultSet, Statement statement, Connection connection){
        if (resultSet != null){
            try {
                resultSet.clearWarnings();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (statement != null){
            try {
                statement.clearWarnings();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection != null){
            try {
                connection.clearWarnings();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

三、建立student数据库和表

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

四、创建Entity:Student

package com.springboot.domain;


public class Student {
    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

五创建Student的dao接口和实现
接口:StudentDAO

package com.springboot.dao;

import com.springboot.domain.Student;
import java.util.List;

public interface StudentDAO {
    //查询所有学生
    public List query();

    //新增学生
    public void save(Student student);
}

实现:StudentDAOImpl

package com.springboot.dao;

import com.springboot.domain.Student;
import com.springboot.utils.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class StudentDAOImpl implements StudentDAO {
    @Override
    public List query() {

        ArrayList students = new ArrayList<>();

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        String sql = "select id, name, age from student";

        try {
                connection = JDBCUtil.getConnection();
                preparedStatement = connection.prepareStatement(sql);
                resultSet = preparedStatement.executeQuery();

                Student student = null;
                while (resultSet.next()){
                    int id = resultSet.getInt("id");
                    String name = resultSet.getString("name");
                    int age = resultSet.getInt("age");

                    student = new Student();
                    student.setId(id);
                    student.setName(name);
                    student.setAge(age);

                    students.add(student);
                }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.release(resultSet, preparedStatement, connection);
        }
        return students;
    }

    @Override
    public void save(Student student) {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        String sql = "insert into student(name ,age) values (?,?)";
        try {
            connection = JDBCUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,student.getName());
            preparedStatement.setInt(2,student.getAge());
            preparedStatement.executeUpdate();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.release(resultSet, preparedStatement, connection);
        }
    }
}

六、创建StudentDAOImpl的单元测试:StudentDAOImplTest

package com.springboot.utils.dao;

import com.springboot.dao.StudentDAOImpl;
import com.springboot.domain.Student;
import org.junit.Test;

import java.util.List;

public class StudentDAOImplTest {

    // 查询所有记录
    @Test
    public void testQuery(){
        StudentDAOImpl studentDAO = new StudentDAOImpl();
        List students = studentDAO.query();
        for (Student student:students){
            System.out.println("id"+student.getId()
                    +"name"+student.getName()
                    +"age"+student.getAge()
            );
        }

    }

    // 新增一个记录
    @Test
    public void testSave(){
        Student student = new Student();
        student.setName("小七");
        student.setAge(25);
        StudentDAOImpl studentDAO = new StudentDAOImpl();
        studentDAO.save(student);
    }
}



附:将数据库连接信息放到配置文件里的写法

  • 修改代码成如下内容
        InputStream inputStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(inputStream);

        String url = properties.getProperty("jdbc.url");
        String user = ("jdbc.user");
        String password = ("jdbc.password");
        String driverClass = ("jdbc.driverClass");
  • resources目录新建db.properties 数据库连接配置文件
jdbc.url = jdbc:mysql:///student;
jdbc.user = root;
jdbc.password = root;
jdbc.driverClass = com.mysql.jdbc.Driver;

你可能感兴趣的:(Spring Data 01 :JDBC 访问 MySQL)