我们来讲解无框架的,使用druid连接池的例子.
-
引进jar包,如果你有maven的话添加如下配置,
//这是druid的依赖配置
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency>
如果你没有使用maven,去百度搜索druid的jar包下载.
2.添加数据连接池的文件
在resource文件夹下添加db_server.properties文件.
文件内容
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://{主机地址}/{数据库名}?useUnicode=true&characterEncoding=UTF8&useSSL=true username=root password=password filters=stat initialSize=2 maxActive=300 maxWait=60000 timeBetweenEvictionRunsMillis=60000 minEvictableIdleTimeMillis=300000 validationQuery=SELECT 1 testWhileIdle=true testOnBorrow=false testOnReturn=false poolPreparedStatements=false maxPoolPreparedStatementPerConnectionSize=200
3.添加使用该连接池的类
package action; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.sql.SQLException; import java.util.Properties; import org.apache.log4j.Logger; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; import com.alibaba.druid.pool.DruidPooledConnection; /** * 要实现单例模式,保证全局只有一个数据库连接池 */ public class DBPoolConnection { private static DBPoolConnection dbPoolConnection = null; private static DruidDataSource druidDataSource = null; static { Properties properties = loadPropertiesFile("classes/db_server.properties"); try { druidDataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties); //DruidDataSrouce工厂模式 } catch (Exception e) { } } /** * 数据库连接池单例 * @return */ public static synchronized DBPoolConnection getInstance(){ if (null == dbPoolConnection){ dbPoolConnection = new DBPoolConnection(); } return dbPoolConnection; } /** * 返回druid数据库连接 * @return * @throws SQLException */ public DruidPooledConnection getConnection() throws SQLException{ return druidDataSource.getConnection(); } /** * @param string 配置文件名 * @return Properties对象 */ private static Properties loadPropertiesFile(String fullFile) { String webRootPath = null; if (null == fullFile || fullFile.equals("")){ throw new IllegalArgumentException("Properties file path can not be null" + fullFile); } webRootPath = DBPoolConnection.class.getClassLoader().getResource("").getPath(); //System.out.println("rootPathis:"+webRootPath); webRootPath = new File(webRootPath).getParent(); InputStream inputStream = null; Properties p =null; try { inputStream = new FileInputStream(new File(webRootPath + File.separator + fullFile)); p = new Properties(); p.load(inputStream); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != inputStream){ inputStream.close(); } } catch (Exception e) { e.printStackTrace(); } } return p; } }
这里的路径一定要填写清楚,如果你使用的是idea,这样一般是没有错误的,如果你使用的是别的ide,哪有可能报错.
这里的resource一定要标记好是资源文件夹.