Java | Detailed Java connection to MySQL, writing JdbcUtils tool class, using database connection pool, using JavaTemplate

1. Connect to the mysql database

        step:

        1. Start MySQL: Open the cmd command line as an administrator , and enter net start mysql

        2. Create a table in MySQL for subsequent operations. Here I created a user table with three fields: id, name, and password.

        3. Import the jar package

        (1) Create a new project and create a lib package under the project to store the required jar packages

         (2) Copy the mysql driver package mysql-connector-j-8.0.31.jar to the lib directory. Right-click the jar package and click Add as Library.

         After adding, a small triangle appears next to the jar package, you can click to view the contents inside, and the import is successful.

mysql driver jar package download:

        Official website: https://dev.mysql.com/downloads/

        CSDN: mysql-connector-j-8.0.31-Java Document Class Resources-CSDN Library

        4. Create class Demo01.java for writing database connection code

        5. Register the driver

Class.forName("com.mysql.cj.jdbc.Driver");

        6. Obtain the database connection object
        method 1:

private static final String URL = "jdbc:mysql://localhost:3306/db1";
private static final String USER = "root";
private static final String PASSWORD = "root";

... ...

Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);

        Method 2:

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?user=root&password=root");

        Method 3:

Properties p = new Properties();
p.setProperty("user","root");
p.setProperty("password","root")
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", p);

        [Note] You need to fill in 3 parameters, which are the database connection URL, user name, and password, and you need to fill in your own.

                 The composition of the URL:

jdbc:mysql:// localhost:3306  /     db1
   协议         IP地址   端口  要连接的数据库名称

        7. Get the object that executes the SQL statement

Statement stat = conn.createStatement();

        8. Execute SQL statements

        Addition, deletion and modification: executeUpdate

stat.executeUpdate("insert into user value(1,'admin','root')");
stat.executeUpdate("update user set name = 'sunny' where id = 1");
stat.executeUpdate("delete from user where id = 1");

        Check: executeQuery

ResultSet rs = stat.executeQuery("select * from user");
while (rs.next()){
    int id = rs.getInt("id");
    String name = rs.getString("name");
    String password = rs.getString("password");
    System.out.println("id="+id+",name="+name+",password="+password);
}

         Method analysis:

  • rs.next —— Determine whether there is a next record in the result set, return boolean type.
  • rs.getInt —— String or int type parameters can be passed in. The String type parameter is the corresponding column name of the data table, and the int type parameter is the corresponding column number of the data table. It is recommended to pass in the String type. Returns data of type int.
  • rs.getString —— You can pass in parameters of type String or int. The parameter of type String is the corresponding column name of the data table, and the parameter of type int is the number of corresponding columns of the data table. It is recommended to pass in the type of String. Returns data of type String.

      9. Release the connection

rs.close();
stat.close();
conn.close();

        Full code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Demo01 {
    private static final String URL = "jdbc:mysql://localhost:3306/db1";
    private static final String USER = "root";
    private static final String PASSWORD = "root";

    public static void main(String[] args) throws Exception {
        // 注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

        // 获取数据库连接对象
        // 方法1
        Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
        // 方法2
        /*Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?user=root&password=root");*/
        // 方法3
        /*
        Properties p = new Properties();
        p.setProperty("user","root");
        p.setProperty("password","root")
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", p);
        */

        // 获取执行SQL语句的对象
        Statement stat = conn.createStatement();

        // 执行SQL语句
        stat.executeUpdate("insert into user value(1,'admin','root')");
        stat.executeUpdate("update user set name = 'sunny' where id = 1");
        stat.executeUpdate("delete from user where id = 1");

        ResultSet rs = stat.executeQuery("select * from user");
        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String password = rs.getString("password");
            System.out.println("id=" + id + ",name=" + name + ",password=" + password);
        }

        // 释放连接
        rs.close();
        stat.close();
        conn.close();
    }
}

2. Write and use tool classes

        Observing the above code, we can find that, except for the different SQL statements, the format of other codes is basically fixed. We can write a tool class that provides related methods such as obtaining database connection objects and closing database-related resources.

        1. Write the tool class JdbcUtils.java

        Create a Utils folder and put all code-related tools in it. Write JdbcUtils.java, the code first runs the statement of the static code block class to obtain the database connection object.

import java.sql.*;

public class JdbcUtils {
    private static final String driver = "com.mysql.cj.jdbc.Driver";
    private static final String url = "jdbc:mysql://localhost:3306/db1";
    private static final String name = "root";
    private static final String password = "root";
    private static final Connection conn;
    
    static {
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, name, password);
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取数据库连接对象
     * @return 数据库连接对象
     */
    public static Connection getConnect() {
        return conn;
    }

    /**
     * 关闭数据库相关资源
     * @param conn 数据库连接对象
     * @param ps sql语句执行对象
     * @param rs 查询结果集
     */
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            if (conn != null) conn.close();
            if (ps != null) ps.close();
            if (rs != null) rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭数据库相关资源
     * @param conn 数据库连接对象
     * @param ps sql语句执行对象
     */
    public static void close(Connection conn, PreparedStatement ps) {
        close(conn, ps, null);
    }

    /**
     * 关闭数据库相关资源
     * @param conn 数据库连接对象
     * @param rs 查询结果集
     */
    public static void close(Connection conn, ResultSet rs) {
        close(conn, null, rs);
    }
}

        2. Decoupling code

        Analyzing the tool class, you can find that the relevant parameters about the database connection, such as driver, url, user, password, etc., are all written in the code, and the coupling of the program is high . Variables can be written in the .properties file, and the program can obtain relevant information by reading the file.

        First create a jdbc.properties resource package, and write related parameters in the form of "key = value".

          jdbc.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db1
name=root
password=root

        JdbcUtils.java

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

public class JdbcUtils {
    private static final String driver;
    private static final String url;
    private static final String name;
    private static final String password;

    static {
        try {
            Properties p = new Properties();
            p.load(JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            driver = p.getProperty("driver");
            url = p.getProperty("url");
            name = p.getProperty("name");
            password = p.getProperty("password");

            Class.forName(driver);
        } catch (ClassNotFoundException | IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取数据库连接对象
     * @return 数据库连接对象
     * @throws Exception 获取失败
     */
    public static Connection getConnect() throws Exception {
        return DriverManager.getConnection(url, name, password);
    }

    /**
     * 关闭数据库相关资源
     * @param conn 数据库连接对象
     * @param ps sql语句执行对象
     * @param rs 查询结果集
     */
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            if (conn != null) conn.close();
            if (ps != null) ps.close();
            if (rs != null) rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭数据库相关资源
     * @param conn 数据库连接对象
     * @param ps sql语句执行对象
     */
    public static void close(Connection conn, PreparedStatement ps) {
        close(conn, ps, null);
    }

    /**
     * 关闭数据库相关资源
     * @param conn 数据库连接对象
     * @param rs 查询结果集
     */
    public static void close(Connection conn, ResultSet rs) {
        close(conn, null, rs);
    }
}

        3. Use tools

import Utils.JdbcUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class JdbcUtilsDemo {
    public static void main(String[] args) throws Exception {
        query();
    }
    public static void query() throws Exception {
        Connection conn = JdbcUtils.getConnect();
        Statement stat = conn.createStatement();

        ResultSet rs = stat.executeQuery("select * from user");
        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String password = rs.getString("password");
            System.out.println("id=" + id + ",name=" + name + ",password=" + password);
        }

        JdbcUtils.close(conn, rs);
    }
}

Third, use the database connection pool

        The database connection pool is a container for storing database connection objects . You can imagine it as a pool with several connection objects installed in advance. When you need to connect to an object, you can get it directly from the pool and return it when you are done using it. In this way, when the program is running, there is no need to create a database connection object by yourself, thereby improving the operating efficiency. Commonly used JDBC connection pools include C3P0 and Druid.

        1. Simple database connection pool

        Write a simple database connection pool to understand the principle.

import Utils.JdbcUtils;

import java.sql.Connection;
import java.util.LinkedList;

public class SimpleConnectPool {
    private static LinkedList<Connection> pool = new LinkedList<>();

    static {
        try {
            for (int i = 1; i <= 5; i++) {
                // 获取数据库连接对象
                Connection conn = JdbcUtils.getConnect();
                // 将连接对象放到 pool 中
                pool.add(conn);
            }
        } catch (Exception e) {
            System.out.println("数据库连接池初始化失败!");
        }
    }

    // 提供 获取数据库连接对象 的方法(pool删除)
    public static synchronized Connection getConnect(){
        if(pool.size() > 0){
            return pool.removeFirst();
        }
        throw new RuntimeException("数据库连接池中 对象已用完");
    }

    // 提供 归还数据库连接对象 的方法(pool添加)
    public static void close(Connection conn){
        pool.addLast(conn);
    }
}

        use the connection pool

import java.sql.Connection;

public class SimpleConnectPoolDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 6; i++) {
            Connection conn = SimpleConnectPool.getConnect();
            System.out.printf("第" + i + "次获取:" + conn+"\n");
            if (i == 3) {
                SimpleConnectPool.close(conn);
                System.out.printf("第" + i + "次归还:" + conn+"\n");
            }
        }
    }
}

        2. Use C3P0 database connection pool

        step:

                (1) Import the jar package. The import method is the same as the import of the mysql driver package. Note that this time, in addition to importing a jar package, an xml configuration file needs to be imported, namely the following two files.        

C3P0 Download: c3p0-0.9.5.2-Java Documentation Resources-CSDN Library                 

                (2) Write the c3p0-config.xml configuration file. Open c3p0-config.xml, and modify the 4 parameters related to the database connection to your own. C3P0 will connect to your mysql database according to the parameters in this configuration file.

                [Note] The configuration file needs to be placed in the src directory .

<?xml version="1.0" encoding="utf-8"?>
<c3p0-config>
  <default-config>
    <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/db1</property>
    <property name="user">root</property>
    <property name="password">root</property>
    
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">10</property>
    <property name="checkoutTimeout">3000</property>
  </default-config>

  <named-config name="otherc3p0"> 
  </named-config>
</c3p0-config>

                (3) Create the C3P0Demo1 class and write related codes.

import com.mchange.v2.c3p0.ComboPooledDataSource;

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

public class C3P0Demo1 {
    public static void main(String[] args) throws SQLException {
        // 创建数据库连接池对象
        DataSource dataSource = new ComboPooledDataSource();

        // 获取数据库连接对象
        Connection conn = dataSource.getConnection();
        System.out.println(conn);

        // 归还连接
        conn.close();
    }
}

                (4) You can also set the database connection related parameters directly in the code without writing the c3p0-config.xml configuration file. Create the C3P0Demo2 class and write related codes.

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

public class C3P0Demo2 {
    public static void main(String[] args) throws PropertyVetoException, SQLException {
        // 创建数据库连接池对象
        ComboPooledDataSource dataSource = new ComboPooledDataSource();

        // 配置参数信息
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/db1");
        dataSource.setUser("root");
        dataSource.setPassword("root");

        // 获取数据库连接对象
        Connection conn = dataSource.getConnection();
        System.out.println(conn);

        // 归还连接
        conn.close();
    }
}

        3. Use Druid database connection pool

        step:

                (1) Import the jar package. The import method is the same as that of the mysql driver package. Note that this time, in addition to importing a jar package, a properties configuration file needs to be imported, namely the following two files.        

 Druid Download: druid-1.0.9-Java Documentation Resources-CSDN Library

                (2) Write the druid.properties configuration file. Open druid.properties, and modify the parameters related to the database connection to your own. Druid will connect to your mysql database according to the parameters in this configuration file.

                [Note] The configuration file needs to be placed in the src directory .

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db1
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000

filters=stat
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200

                (3) Create the DruidDemo1 class and write related codes.

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.Properties;

public class DruidDemo1 {
    public static void main(String[] args) throws Exception {
        // 创建数据库连接池对象
        Properties p = new Properties();
        p.load(DruidDemo1.class.getClassLoader().getResourceAsStream("druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(p);

        // 获取数据库连接对象
        Connection conn = dataSource.getConnection();
        System.out.println(conn);

        // 归还连接
        conn.close();
    }
}

                (4) Similarly, you can also directly set the database connection related parameters in the code without writing the druid.properties configuration file. Create the DruidDemo2 class and write related codes.

import com.alibaba.druid.pool.DruidDataSource;

import java.sql.Connection;

public class DruidDemo2 {
    public static void main(String[] args) throws Exception {
        // 创建数据库连接池对象
        DruidDataSource dataSource = new DruidDataSource();

        // 配置参数信息
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/db1");
        dataSource.setUsername("root");
        dataSource.setPassword("root");

        // 获取数据库连接对象
        Connection conn = dataSource.getConnection();
        System.out.println(conn);

        // 归还连接
        conn.close();
    }
}

        4. Write Druid tools

        Of course, you can write Druid utility classes like the above JdbcUtils. The tool class code is placed in the Utils directory. What I use here is the way of writing configuration files, and the configuration files do not need to be changed.

package Utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtils {
    public static DataSource dataSource;

    static {
        try {
            Properties p = new Properties();
            p.load(DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 获取数据库连接池对象的方法
    public static DataSource getDataSource() {
        return dataSource;
    }

    // 获取数据库连接对象的方法
    public static Connection getConnection() throws Exception {
        return dataSource.getConnection();
    }

    // 归还数据库连接对象的方法
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            // 归还数据库连接对象
            if (conn != null) conn.close();
            // 释放sql语句执行对象
            if (ps != null) ps.close();
            // 释放查询结果集
            if (rs != null) rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

        use:

package Pool;

import Utils.DruidUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DruidUtilsDemo3 {
    public static void main(String[] args) throws Exception {
        // 获取数据库连接对象
        Connection conn = DruidUtils.getConnection();

        // 获取执行sql语句执行对象
        PreparedStatement ps = conn.prepareStatement("select * from user");

        // 执行sql语句,获得结果集
        ResultSet rs = ps.executeQuery();

        // 解析结果集
        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            String password = rs.getString("password");
            System.out.println("id=" + id + ",name=" + name + ",password=" + password);
        }

        // 归还连接,释放sql语句执行对象、结果集
        DruidUtils.close(conn,ps,rs);
    }
}

Fourth, use JavaTemplate

JavaTemplate is an ORM -based tool class         that encapsulates JDBC by the Spring framework . It can help us simplify the code.

        1. ORM object relational mapping idea (Object Relational Mapping)

        Take us browsing the website as an example, when we send a request to the server of the website (such as login operation), the server will receive information related to our request (such as login user name, password). The idea of ​​ORM is to first encapsulate this information into a class named user. The fields in this class, such as id, name, password, etc., will correspond to the column names of the tables in the database one by one. Through JDBC decapsulation, reflection and other technologies, the data is passed to the database and returned to the server. 

        2. Easy to use

        step:

        (1) Import the jar package. Five packages need to be imported, and the package names are as follows:

 Download JavaTemplate: JdbcTemplate-Java Document Class Resources-CSDN Library

        (2) Create a User class, and the fields in the class correspond to the tables in your database one by one. It is recommended to use tools to automatically generate this code, try not to write it yourself.

public class User {
    private int id;
    private String name;
    private String password;

    public User() {
    }
    public User(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public void setId(int id) {
        this.id = id;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public String getPassword() {
        return password;
    }

    @Override
    public String toString() {
        return "User{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + '}';
    }
}

         [Note] Don't forget the parameterless construction ! Don't forget to miss the setXXX(), getXXX() methods !

        (3) Create the JdbcTemplateDemo class and write related codes

        (4) Create a database connection pool object (C3P0 or Druid)

                C3P0:

DataSource dataSource = new ComboPooledDataSource();

                Druid:

Properties p = new Properties();
p.load(JdbcTemplateDemo.class.getClassLoader().getResourceAsStream("druid.properties"));
DataSource dataSource = DruidDataSourceFactory.createDataSource(p);

        (5) Create a JdbcTemplate object and encapsulate the database connection pool object into the JdbcTemplate object

                Method 1: Assignment through the parameterized construction of JdbcTemplate

JdbcTemplate jt = new JdbcTemplate(dataSource);

                Method 2: Assign a value through the setDataSource method of JdbcTemplate

JdbcTemplate jt = new JdbcTemplate();
jt.setDataSource(dataSource);

        (6) execute sql statement

        Additions, deletions and modifications:

User user = new User(1,"admin","1234");
jt.update("insert into user value (?,?,?)",user.getId(),user.getName(),user.getPassword());
jt.update("update user set name = ? where id = ?", user.getName(), user.getId());
jt.update("delete from user where id = ?", user.getId());

        check:

  •  Query a piece of data
int id = 1; // 仅为简单示范
User user = jt.queryForObject("select * from user where id = ?",new BeanPropertyRowMapper<>(User.class),id);
System.out.println(user);
  • Query multiple records
List<User> users = jt.query("select * from user", new BeanPropertyRowMapper<>(User.class));
for (User a : users) System.out.println(a);
  • Query a data: query the name value of id=1
int id = 1; // 仅为简单示范
String name = jt.queryForObject("select name from user where id = ?", String.class, id);
System.out.println(name);
  • Query a data: how many records are there in the query table
int count = jt.queryForObject("select count(*) from user",int.class);
System.out.println(count);

        (7) All codes:

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.List;

public class JdbcTemplateDemo {
    public static void main(String[] args) throws Exception {
        // 1.创建数据库连接池对象
        /* C3P0 */
        DataSource dataSource = new ComboPooledDataSource();

        /* Druid */
        /*
        Properties p = new Properties();
        p.load(JdbcTemplateDemo.class.getClassLoader().getResourceAsStream("druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(p);
        */


        // 2.创建 JdbcTemplate 对象,将数据库连接池封装到 JdbcTemplate 对象
        /* 方法一 : 提供有参构造赋值 */
        // JdbcTemplate jt = new JdbcTemplate(dataSource);

        /* 方法二 : 通过setDataSource赋值 */
        JdbcTemplate jt = new JdbcTemplate();
        jt.setDataSource(dataSource);


        // 3.执行 sql 语句
        /* 增删改 */
        User user1 = new User(1,"admin","1234");  // 仅为简单示范
        jt.update("insert into user value (?,?,?)", user1.getId(), user1.getName(),user1.getPassword());
        jt.update("update user set name = ? where id = ?", user1.getName(), user1.getId());
        jt.update("delete from user where id = ?", user1.getId());

        /* 查 */
        // 查询一条数据
        int id = 1; // 仅为简单示范
        User user2 = jt.queryForObject("select * from user where id = ?",new BeanPropertyRowMapper<>(User.class),id);
        System.out.println(user2);

        // 查询多条记录
        List<User> users = jt.query("select * from user", new BeanPropertyRowMapper<>(User.class));
        for (User a : users) System.out.println(a);


        // 查询一个数据 : 查询 id=1 的 name 值
        String name = jt.queryForObject("select name from user where id = ?", String.class, 1);
        System.out.println(name);

        // 查询一个数据 : 查询表中有多少条记录
        int count = jt.queryForObject("select count(*) from user",int.class);
        System.out.println(count);
    }
}
public class User {
    private int id;
    private String name;
    private String password;

    public User() {
    }
    public User(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public void setId(int id) {
        this.id = id;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public String getPassword() {
        return password;
    }

    @Override
    public String toString() {
        return "User{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + '}';
    }
}

        3. Use in actual projects

        Project structure:

         (1) UserDao class

import java.util.List;

public interface UserDao {
    // 添加用户
    void add(User user);

    // 修改用户
    void update(User user);

    // 删除用户
    void delete(int id);

    // 查询所有
    List<User> findAll();

    // 查询一条数据
    User findById(int id);
}

        (2) UserDaoImpl class

import Utils.DruidUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class UserDaoImpl implements UserDao {
    // 创建 JdbcTemplate 对象
    private final JdbcTemplate jt = new JdbcTemplate(DruidUtils.getDataSource());

    @Override
    public void add(User user) {
        jt.update("insert into user values(?,?,?)", user.getId(), user.getName(), user.getPassword());
    }

    @Override
    public void update(User user) {
        jt.update("update user set name = ?,password = ? where id = ?", user.getName(), user.getPassword(), user.getId());
    }

    @Override
    public void delete(int id) {
        jt.update("delete from user where id = ?", id);
    }

    @Override
    public List<User> findAll() {
        List<User> users = jt.query("select * from user", new BeanPropertyRowMapper<>(User.class));
        return users;
    }

    @Override
    public User findById(int id) {
        User user = jt.queryForObject("select * from user where id = ?", new BeanPropertyRowMapper<>(User.class), id);
        return user;
    }
}

        (3) User class

import java.io.Serializable;

public class User implements Serializable {
    private int id;
    private String name;
    private String password;

    public User() {
    }
    public User(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }

    public void setId(int id) {
        this.id = id;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public String getPassword() {
        return password;
    }

    @Override
    public String toString() {
        return "User{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + '}';
    }
}

        (4) DruidUtils class

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtils {
    public static DataSource dataSource;

    static {
        try {
            Properties p = new Properties();
            p.load(DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 获取数据库连接池对象的方法
    public static DataSource getDataSource() {
        return dataSource;
    }

    // 获取数据库连接对象的方法
    public static Connection getConnection() throws Exception {
        return dataSource.getConnection();
    }

    // 归还数据库连接对象的方法
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            // 归还数据库连接对象
            if (conn != null) conn.close();
            // 释放sql语句执行对象
            if (ps != null) ps.close();
            // 释放查询结果集
            if (rs != null) rs.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

        (5) UserTest class

import org.junit.Test;

import java.util.List;

public class UserTest {
    // 创建 Dao 对象
    private final UserDao userDao = new UserDaoImpl();

    @Test
    public void add() {
        User user = new User(1, "ketty", "eee");
        userDao.add(user);
    }

    @Test
    public void update() {
        User user = new User(1, "hello", "root");
        userDao.update(user);
    }

    @Test
    public void delete() {
        userDao.delete(1);
    }

    @Test
    public void findAll() {
        List<User> users = userDao.findAll();
        for (User a : users) {
            System.out.println(a);
        }
    }

    @Test
    public void findById() {
        User user = userDao.findById(1);
        System.out.println(user);
    }

        JUnit's @Test is used in the UserTest class for faster testing. You can also test in the main method.

Guess you like

Origin blog.csdn.net/sun80760/article/details/128425470