一:添加相应依赖
druid-1.0.9.jar;mysql-connector-java-5.1.48-bin.jar二:编写properties文件
放置位置在src中;driverClassName=com.mysql.jdbc.Driverurl=jdbc:mysql://localhost:3306(“端口号”)/数据库名username=root(账户)password=mysql123(密码)initialSize=5maxActive=10maxWait=1000
注意:本端口号不是Tomcat的端口号(8080),而是数据库的端口号;
三:编写Druid实体类
import com.alibaba.druid.pool.DruidDataSourceFactory;import javax.sql.DataSource;import java.io.IOException;import java.io.InputStream;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;/*** @author Damon Wang* @data /9/15 08:47:26* 1. 声明静态数据源成员变量* 2. 创建连接池对象* 3. 定义公有的得到数据源的方法* 4. 定义得到连接对象的方法* 5. 定义关闭资源的方法*/public class DruidUtils {// Create a static variable ds;private static DataSource ds;// create connector object;static {InputStream is = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");Properties pp = new Properties();try {// create connector pool and properties's parameter;pp.load(is);ds = DruidDataSourceFactory.createDataSource(pp);}catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}// Create public the way of getting DataSource;public static DataSource getDataSource() {return ds;}// Create object the way of connector;public static Connection getConnection() throws SQLException {return ds.getConnection();}// Create thr way of turning of connector datasource;public static void close(Connection conn, Statement stmt, ResultSet rs){if (rs != null){try {rs.close();} catch (SQLException e) {e.printStackTrace();}}if (stmt != null){try{stmt.close();} catch (SQLException e) {e.printStackTrace();}}if (rs != null){try {rs.close();} catch (SQLException e) {e.printStackTrace();}}}// Reload the way of turning of;public static void close(Connection conn,Statement stmt) {close(conn, stmt);}// Create the test Case;public static void main(String[] args)throws SQLException {System.out.println(ds.getConnection());}}
四:测试结果:运行Druid类的mian()方法。
总结:Druid数据库连接池也是Java单例模式的一种实际运用;
需要资源的同学,可以私信我;如果觉得《Druid数据库连接池使用参考》对你有帮助,请点赞、收藏,并留下你的观点哦!