配置文件
db.driver=com.mysql.jdbc.Driver db.url=jdbc\:mysql\://localhost\:3306/mybase db.user=root db.pswd=[email protected] #-- 连接池初始化连接数 -- dataSource.initialSize=10 #-- 最大空闲连接 -- dataSource.maxIdle=20 #-- 最小空闲连接 -- dataSource.minIdle=5 #-- 最大连接数 -- dataSource.maxActive=50 #-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -- dataSource.wait=500
使用普通方式链接数据库
package com.globalroam.util; import java.io.IOException; import java.util.Properties; public class DbUtil { private static Properties properties = new Properties(); public static String driver = null; public static String url = null; public static String user = null; public static String pswd = null; static{ try { properties.load(DbUtil.class.getClassLoader().getResourceAsStream("resource/db.properties")); driver = properties.getProperty("db.driver"); url = properties.getProperty("db.url"); user = properties.getProperty("db.user"); pswd = properties.getProperty("db.pswd"); } catch (IOException e) { e.printStackTrace(); } } }
使用连接池获取Connection
package com.globalroam.util; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import org.apache.commons.dbcp.BasicDataSource; public class DBConnectionPool { private static BasicDataSource dataSource = null; private static Properties properties = new Properties(); //private static Logger logger = Logger.; public static void initDataSource() { try { properties.load(DBConnectionPool.class.getClass().getResourceAsStream("resource/db.properties")); dataSource = new BasicDataSource(); dataSource.setDriverClassName(properties.getProperty("db.driver")); dataSource.setUrl(properties.getProperty("db.url")); dataSource.setUsername(properties.getProperty("db.user")); dataSource.setPassword(properties.getProperty("db.pswd")); if(properties.getProperty("dataSource.initialSize") != null) { dataSource.setInitialSize(Integer.parseInt(properties.getProperty("dataSource.initialSize"))); } if(properties.getProperty("dataSource.maxIdle") != null) { dataSource.setMaxIdle(Integer.parseInt(properties.getProperty("dataSource.maxIdle"))); } if(properties.getProperty("dataSource.minIdle") != null) { dataSource.setMinIdle(Integer.parseInt(properties.getProperty("dataSource.minIdle"))); } if(properties.getProperty("dataSource.maxActive") != null && "0".equals(properties.getProperty("dataSource.maxActive"))) { dataSource.setMaxActive(Integer.parseInt(properties.getProperty("dataSource.maxActive"))); } if(properties.getProperty("dataSource.wait") != null) { dataSource.setMaxWait(Integer.parseInt(properties.getProperty("dataSource.wait"))); } } catch (IOException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { Connection conn = null; if(dataSource == null) { initDataSource(); } if(dataSource != null) { conn = dataSource.getConnection(); } return conn; } }
时间: 2024-10-01 02:52:02