JavaWeb数据库连接封装类

useSSL=false 连接配置详解

来源:https://blog.csdn.net/qq_42782063/article/details/90714658
web应用中连接mysql数据库时后台会出现这样的提示:

Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+,
5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn’t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false’. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

原因是MySQL在高版本需要指明是否进行SSL连接。

SSL协议提供服务主要: 		
       1)认证用户服务器,确保数据发送到正确的服务器;    .
       2)加密数据,防止数据传输途中被窃取使用;
       3)维护数据完整性,验证数据在传输过程中是否丢失;

 当前支持SSL协议两层:
   	 	SSL记录协议(SSL Record Protocol):建立靠传输协议(TCP)高层协议提供数据封装、压缩、加密等基本功能支持
	    SSL握手协议(SSL Handshake Protocol):建立SSL记录协议用于实际数据传输始前通讯双进行身份认证、协商加密
	    算法、 交换加密密钥等。

解决方案如下:
在mysql连接字符串url中加入ssl=true或者false即可,如下所示。
url=jdbc:mysql://127.0.0.1:3306/school?useSSL=true

useUnicode=true&characterEncoding=UTF-8 的作用

来源:https://blog.csdn.net/qq_37745470/article/details/86574493
我们在连接mysql数据库的时候一般都会在url后面添加useUnicode=true&characterEncoding=UTF-8 ,但是问什么要添加呢?

添加的作用是:指定字符的编码、解码格式。

例如:mysql数据库用的是gbk编码,而项目数据库用的是utf-8编码。这时候如果添加了useUnicode=true&characterEncoding=UTF-8 ,那么作用有如下两个方面:
     
存数据时:
	数据库在存放项目数据的时候会先用UTF-8格式将数据解码成字节码,然后再将解码后的字节码重新使用GBK编码存放到数据库中。

取数据时:
	在从数据库中取数据的时候,数据库会先将数据库中的数据按GBK格式解码成字节码,然后再将解码后的字节码重新按UTF-8格式编码数据,最后再将数据返回给客户端。

解决方法:
jdbc:mysql://localhost:3306/school?useSSL=false&useUnicode=true&characterEncoding=UTF-8

JDBCUtils

普通方式

package com.myaijarvis.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUtils {
    
    
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
    
    
        Class.forName("com.mysql.jdbc.Driver");
        String url="jdbc:mysql://localhost:3306/school?useSSL=false&useUnicode=true&characterEncoding=UTF-8";
        String username="root";
        String password="123456";
        Connection connection = DriverManager.getConnection(url, username, password);
        connection.setAutoCommit(false);//注意:为防止事务自动提交,我们习惯在这里将事务的提交方式改为手动提交
        return connection;
    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
    
    
        System.out.println(getConnection());
    }
}

常用方式

package com.myaijarvis.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCUtils {
    
    

    private static Properties prop = new Properties();
    private static String driverClass;
    private static String url;
    private static String userName;
    private static String password;
    /**
     * 将读取 Properties定义为静态代码块
     * 让JVM加载类时自动执行这些它,且只被执行一次
     */
    static {
    
    
        InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("config.properties");
        try {
    
    
            prop.load(is);
            driverClass = prop.getProperty("driverClass");
            url = prop.getProperty("url");
            userName = prop.getProperty("userName");
            password = prop.getProperty("password");
            Class.forName(driverClass);
        }catch (Exception e) {
    
    
            e.printStackTrace();
        }finally{
    
    
            if(is!=null){
    
    
                try {
    
    is.close();}
                catch (IOException e){
    
    e.printStackTrace();}
            }
        }
    }

    /**
     * 将读取 getConnection定义为静态方法
     * 以保证同一事务使用的是同一个连接
     */
    public static Connection getConnection(){
    
    
        Connection conn=null;
        try {
    
    
            conn = DriverManager.getConnection(url,userName,password);
            conn.setAutoCommit(false);//注意:为防止事务自动提交,我们习惯在这里将事务的提交方式改为手动提交
            System.out.println("DBUtil: 连接数据库成功!");
        }catch (SQLException e) {
    
    
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
        return conn;
    }

    /**
     * 将 closeConnection也定义为静态方法
     */
    public static void closeConnection(Connection conn) {
    
    
        if (conn != null) {
    
    
            try {
    
    //关闭连接
                conn.close();
            } catch (SQLException e) {
    
    
                e.printStackTrace();
            }
        }
    }
     public static void release(PreparedStatement perStmt, Connection conn){
    
    
        if(perStmt!=null){
    
    
            try {
    
    
                perStmt.close();
            }catch (SQLException e){
    
    
                e.printStackTrace();
            }
            perStmt=null;
        }
        closeConnection(conn);
    }
    public static void release(ResultSet rs, PreparedStatement perStmt, Connection conn){
    
    
        if(rs!=null){
    
    
            try {
    
    
                rs.close();
            }catch (SQLException e){
    
    
                e.printStackTrace();
            }
            rs=null;
        }
        release(perStmt,conn);
    }
}

对于java工程和web工程来说加载Properties文件有不同的加载方式

  • Java工程里可以直接new来加载配置文件
    Properties properties = new Properties();
    InputStream is = new FileInputStream(“config.properties”);
  • JavaWeb使用类加载器,去读取src底下的资源文件。 后面在servlet,web工程需要使用类加载器来加载配置文件
    InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream(“config.properties”);
    properties.load(is);

config.properties

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/school?useSSL=false&useUnicode=true&characterEncoding=UTF-8
userName=root
password=123456

DBCPUtils

普通方式

package com.myaijarvis.util;

import org.apache.commons.dbcp.BasicDataSource;

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

public class DBCPUtils {
    
    
    public static DataSource dataSource=null;
    static {
    
    
        // 获取DBCP数据源
        BasicDataSource basicDataSource = new BasicDataSource();
        // 设置连接数据库的配置信息
        basicDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        basicDataSource.setUrl("jdbc:mysql://localhost:3306/school?useSSL=false&useUnicode=true&characterEncoding=UTF-8");
        basicDataSource.setUsername("root");
        basicDataSource.setPassword("123456");
        // 设置连接池的参数
        basicDataSource.setInitialSize(10);
        basicDataSource.setMaxActive(20);
        basicDataSource.setMinIdle(5);
        // 数据源赋值
        dataSource=basicDataSource;
    }

    public static Connection getConnection(){
    
    
        Connection connection=null;
        try {
    
    
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);//注意:为防止事务自动提交,我们习惯在这里将事务的提交方式改为手动提交
            System.out.println("连接数据库成功!");
        }catch (SQLException e) {
    
    
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
        return connection;
    }
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
    
    
        System.out.println(getConnection());
    }
}

常用方式

package com.myaijarvis.util;

import org.apache.commons.dbcp.BasicDataSourceFactory;

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

public class DBCPUtils {
    
    
    public static DataSource dataSource=null;
    static {
    
    
        Properties properties = new Properties();
        try{
    
    
            // 通过类加载其找到文件路径,读取配置文件
            InputStream in=DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
            // 把文件以输入流的形式加载到配置对象中
            properties.load(in);
            // 数据源赋值
            dataSource= BasicDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
    public static Connection getConnection(){
    
    
        Connection connection=null;
        try {
    
    
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);//注意:为防止事务自动提交,我们习惯在这里将事务的提交方式改为手动提交
            System.out.println("连接数据库成功!");
        }catch (SQLException e) {
    
    
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
        return connection;
    }
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
    
    
        System.out.println(getConnection());
    }
}

db.properties

# 连接设置
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/school?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
# 初始化连接数
initialSize=10
# 最大连接数
maxActive=20
# 最大空闲连接数
maxIdle=5

C3P0Utils

普通方式

package com.myaijarvis.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

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

public class C3P0Utils {
    
    
    public static DataSource dataSource = null;
    static {
    
    
        // 获取C3P0数据源
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        try {
    
    
            // 设置连接数据库的配置信息
            cpds.setDriverClass("com.mysql.jdbc.Driver");
            cpds.setJdbcUrl("jdbc:mysql://localhost:3306/school?useSSL=false&useUnicode=true&characterEncoding=UTF-8");
            cpds.setUser("root");
            cpds.setPassword("123456");
            // 设置连接池的参数
            cpds.setInitialPoolSize(10);
            cpds.setMaxPoolSize(20);
            cpds.setMinPoolSize(5);
            // 数据源赋值
            dataSource = cpds;
        } catch (PropertyVetoException e) {
    
    
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
    
    
        Connection connection = null;
        try {
    
    
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);//注意:为防止事务自动提交,我们习惯在这里将事务的提交方式改为手动提交
            System.out.println("连接数据库成功!");
        } catch (SQLException e) {
    
    
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
        return connection;
    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
    
    
        System.out.println(getConnection());
    }
}

常用方式

package com.myaijarvis.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

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

public class C3P0Utils {
    
    
    public static DataSource dataSource = null;

    static {
    
    
        // 获取C3P0数据源
        ComboPooledDataSource cpds = new ComboPooledDataSource("myConfig");
        // 数据源赋值
        dataSource = cpds;
    }

    public static Connection getConnection() {
    
    
        Connection connection = null;
        try {
    
    
            connection = dataSource.getConnection();
            connection.setAutoCommit(false);//注意:为防止事务自动提交,我们习惯在这里将事务的提交方式改为手动提交
            System.out.println("连接数据库成功!");
        } catch (SQLException e) {
    
    
            e.printStackTrace();
            System.out.println("数据库连接失败");
        }
        return connection;
    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
    
    
        System.out.println(getConnection());
    }
}

c3p0-config

<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
	<!--默认配置-->
	<default-config>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="JdbcUrl">jdbc:mysql://localhost:3306/school?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="checkoutTimeout">30000</property>
		<property name="idleConnectionTestPeriod">30</property>
		<property name="initialPoolSize">3</property>
		<property name="maxIdleTime">30</property>
		<property name="maxPoolSize">100</property>
		<property name="minPoolSize">2</property>
		<property name="maxStatements">200</property>
	</default-config>
	<!-- 自定义配置 -->
	<named-config name="myConfig">
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/school?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8</property>
		<property name="user">root</property>
		<property name="password">123456</property>
		<!-- 如果池中数据连接不够时一次增长多少个 -->
		<property name="acquireIncrement">5</property>
		<!-- 初始化数据库连接池时连接的数量 -->
		<property name="initialPoolSize">20</property>
		<!-- 数据库连接池中的最大的数据库连接数 -->
		<property name="maxPoolSize">25</property>
		<!-- 数据库连接池中的最小的数据库连接数 -->
		<property name="minPoolSize">5</property>
		<!--连接关闭时默认将所有未提交的操作回滚-->
		<property name="autoCommitOnClose">false</property>
	</named-config>
</c3p0-config>

书上代码


import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {
    
    

private static DataSource dataSource = new ComboPooledDataSource();
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

	public static DataSource getDataSource() {
    
    
		return dataSource;
	}
	/**
	 * 当DBUtils需要手动控制事务时,调用该方法获得一个连接
	 * 
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
    
    
		Connection con = tl.get();
		if (con == null) {
    
    
			con = dataSource.getConnection();
			tl.set(con);
		}
		return con;
	}
	/**
	 * 开启事务
	 * 
	 * @throws SQLException
	 */
	public static void startTransaction() throws SQLException {
    
    
		Connection con = getConnection();
		if (con != null)
			con.setAutoCommit(false);
	}
	/**
	 * 从ThreadLocal中释放并且关闭Connection,并结束事务
	 * 
	 * @throws SQLException
	 */
	public static void releaseAndCloseConnection() throws SQLException {
    
    
		Connection con = getConnection();
		if (con != null) {
    
    
			con.commit();
			tl.remove();
			con.close();
		}
	}
	/**
	 * 事务回滚
	 * @throws SQLException 
	 */
	public static void rollback() throws SQLException {
    
    
		Connection con = getConnection();
		if (con != null) {
    
    
			con.rollback();
		}
	}
}

猜你喜欢

转载自blog.csdn.net/Jruo911/article/details/106150769