java使用Druid连接池连接mysql

1.先在mysql创建需要的数据库和表

use book;
create table t_user(
`id` int primary key auto_increment,
`username` varchar(20) not null unique,
`password` varchar(32) not null,
`email` varchar(200)
);
insert into t_user(`username`,`password`,`email`) values(‘admin‘,‘admin‘,‘‘);
select * from t_user;

2.编写与数据库表对应的javaBean对象

package com.atguigu.pojo;
//数据库表对应的javaBean对象
public class User {
    private int id;
    private String username;
    private String password;
    private String email;
    
    public User() {}
    public User(int id, String username, String password, String email) {
        super();
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]";
    }
    

}

3.编写工具类JdbcUtil

3.1先导入需要的jar包(数据库和连接池需要):

java使用Druid连接池连接mysql

3.2、在src源码目录下编写jdbc.properties属性配置文件

initialSize=5maxActive=10driver=com.mysql.cj.jdbc.Driverurl=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&characterEncoding=utf8username=rootpassword=123456

注意:

1.如果你在url这么没有添加“?characterEncoding=utf8”,有可能会出现以下错误:

Unknown initial character set index ‘255‘ received from server. Initial client character set can be forced via the ‘characterEncoding‘ property.

从服务器收到的未知初始字符集索引“255”。初始客户端字符集可以通过“字符编码”属性强制设置。

 2、如果你连接的mysql数据库是8.0及以上的,driver要记得改为:‘com.mysql.cj.jdbc.Driver‘,否则会报错。详细看https://blog.csdn.net/superdangbo/article/details/78732700

3.3、编写数据库工具类JdbcUtil

 Druid数据库连接池有两种使用方式:

1.直接设置数据源参数并建立连接池

2.Properties配置数据源,读取数据源并建立连接池

方式一:直接设置数据源参数并建立连接池

package com.atguigu.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import java.sql.Connection;

public class JDBCUtil {  
        private static DruidDataSource dataSource;
        
        static {        
            try {
                dataSource= new DruidDataSource();

                dataSource.setUrl("jdbc:mysql://localhost:3306/test?serverTimezone=UTC&characterEncoding=utf8");
                dataSource.setUsername("root");
                dataSource.setPassword("123456");
                dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
                dataSource.setInitialSize(5);
                dataSource.setMaxActive(10);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        /**
         * 获取数据库连接池中的连接
         * @return 如果返回null,说明连接失败,有值就是获取连接成功
         */
        public static Connection getConnection() {
            Connection conn=null;
            
            try {
                conn=(Connection)dataSource.getConnection();
            }catch(Exception e) {
                e.printStackTrace();
            }
            
            return conn;
        }
        
        /**
         * 关闭连接,放回数据库连接池
         * @param conn
         */
        public static void close(Connection conn) {
            if(conn!=null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    

}

方式二:Properties配置数据源,读取数据源并建立连接池(Properties文件看3.2)

package com.atguigu.util;

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

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
//import com.mysql.jdbc.Connection;
import java.sql.Connection;
public class JdbcUtil {
    private static DruidDataSource dataSource;
    
    static {        
        try {
            Properties properties=new Properties();
            //读取jdbc.properties属性配置文件
            InputStream is=JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
            //从流中记载数据
            properties.load(is);
            //创建数据库连接池
            dataSource= (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * 获取数据库连接池中的连接
     * @return 如果返回null,说明连接失败,有值就是获取连接成功
     */
    public static Connection getConnection() {
        Connection conn=null;
        try {
            conn=(Connection) dataSource.getConnection();
        }catch(Exception e) {
            e.printStackTrace();
        }
        
        return conn;
    }
    
    /**
     * 关闭连接,放回数据库连接池
     * @param conn
     */
    public static void close(Connection conn) {
        if(conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}

3.4、JdbcUtil测试

package com.atguigu.test;

import org.junit.Test;

import com.alibaba.druid.util.JdbcUtils;
import com.atguigu.util.JdbcUtil;
//import com.mysql.jdbc.Connection;
import java.sql.Connection;
public class JdbcUtilsTest {
    
    public static void main(String []args) {      
            Connection connection = JdbcUtil.getConnection();
            System.out.println(connection);
            JdbcUtils.close(connection);
       
    }

}

结果:

java使用Druid连接池连接mysql

最后:我遇到的坑有无数个,我搞了一下午,才弄好,哭泣。。。。

1、如果你遇到错误:Cause: java.sql.SQLException: Unknown initial character set index ‘255‘ received from server.

可以参考这篇文章:https://blog.csdn.net/Ahuuua/article/details/89071738?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase/

2、如果遇到Client does not support authentication protocol requested by server; consider upgrading MySQL client这个错误,有可能需要把用户密码登录的加密规则还原成mysql_native_password这种加密方式。如何修改可以参考这篇文章:https://blog.csdn.net/numberseven7/article/details/99548745

相关推荐