How to write JdbcUtils database access tools

(A) The basic version of JDBC statements

1, the new jdbc.properties file to connect to the database storage parameters needed in the src directory (Maven project needs to be in resources might otherwise occur can not find the file)
jdbc.properties file:

url=jdbc:mysql://192.168.91.4:3306/myDB?characterEncoding=utf8
user=root
password=ZepngLin_42
driver=com.mysql.cj.jdbc.Driver

2, create JDBCUtils.java file, and acquires the value of the configuration file in a static block of code, and register drive
JDBCUtils.java:

package cn.web.util;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

/**
 * JDBC工具类
 */
public class JDBCUtils {
    private static String url;
    private static String user;
    private static String password;
    private static String driver;
    /**
     * 文件的读取,只需要读取一次即可拿到这些值。使用静态代码块
     */
    static{
        //读取资源文件,获取值。

        try {
            //1. 创建Properties集合类。
            Properties pro = new Properties();

            //获取src路径下的文件的方式--->ClassLoader 类加载器
            ClassLoader classLoader = JDBCUtils.class.getClassLoader();
            URL res  = classLoader.getResource("jdbc.properties");
            String path = res.getPath();
           // System.out.println(path);///D:/IdeaProjects/itcast/out/production/day04_jdbc/jdbc.properties
            //2. 加载文件
           // pro.load(new FileReader("D:\\IdeaProjects\\itcast\\day04_jdbc\\src\\jdbc.properties"));
            pro.load(new FileReader(path));

            //3. 获取数据,赋值
            url = pro.getProperty("url");
            user = pro.getProperty("user");
            password = pro.getProperty("password");
            driver = pro.getProperty("driver");
            //4. 注册驱动
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取连接
     * @return 连接对象
     */
    public static Connection getConnection() throws SQLException {

        return DriverManager.getConnection(url, user, password);
    }

    /**
     * 释放资源
     * @param stmt
     * @param conn
     */
    public static void close(Statement stmt,Connection conn){
        if( stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if( conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 释放资源
     * @param stmt
     * @param conn
     */
    public static void close(ResultSet rs,Statement stmt, Connection conn){
        if( rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if( stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if( conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

(B) using a database connection pool druid

Database Connection Pool
1. concept: in fact, a container (collection), storage containers database connection.
When a good system initialization, the container is created, the container will apply for some of the connection object when the user to access the database to get a connection object from the container, after the user access to finished, the connection object will be returned to the container.
2. Benefits:
1. conserve resources
2. The user access efficiency
3. Implementation:
1. Standard Interface: DataSource javax.sql package under
1. Method:
* Get the connection: the getConnection ()
* return connection: Connection.close (). If the connection object Connection is to obtain from the connection pool, then call Connection.close () method, you will not close the connection. But the return connection
2. Generally, we do not realize it, there are database vendors to achieve
1. C3P0: database connection pool technology
2. Druid: database connection pool implementation technology, provided by Alibaba
Druid:
1. Step:
1. Import jar package-1.0.9.jar Druid
2. define profile:
* is in the form of properties
* can be called any name, can be placed in any directory
3. load the configuration file. The Properties
4. database connection pool object: to get to the plant by DruidDataSourceFactory
5. obtaining a connection: the getConnection
* Code:
// Load Profile 3
the Properties Pro new new = the Properties ();
the InputStream DruidDemo.class.getClassLoader IS = () the getResourceAsStream ( "druid.properties");.
Pro.load (IS);
// get a connection pool object. 4
DS = DruidDataSourceFactory.createDataSource the DataSource (Pro);
.. 5 // get connection
connection ds.getConnection Conn = ();
2. the class definition tool
1. define a class JDBCUtils
2. provide static code block loading configuration files, initialize the connection pool object
providing method
1. obtain connection method: obtaining a connection via a database connection pool
2. releasing resources
3. the method of obtaining the connection pool

package cn.web.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * Druid连接池的工具类
 */
public class JDBCUtils {

    //1.定义成员变量 DataSource
    private static DataSource ds ;

    static{
        try {
            //1.加载配置文件
            Properties pro = new Properties();
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //2.获取DataSource
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /**
     * 释放资源
     */
    public static void close(Statement stmt,Connection conn){
       close(null,stmt,conn);
    }


    public static void close(ResultSet rs , Statement stmt, Connection conn){


        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn != null){
            try {
                conn.close();//归还连接
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 获取连接池方法
     */
    public static DataSource getDataSource(){
        return  ds;
    }

}

Published 42 original articles · won praise 16 · views 3384

Guess you like

Origin blog.csdn.net/qq_41542638/article/details/104452746