我们专注攀枝花网站设计 攀枝花网站制作 攀枝花网站建设
成都网站建设公司服务热线:400-028-6601

网站建设知识

十年网站开发经验 + 多家企业客户 + 靠谱的建站团队

量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决

java链接池的代码 java连接池druid

请问那位可以给个用纯java实现数据库连接池的代码

DataSource ds=null;

成都创新互联是一家专业提供伊金霍洛企业网站建设,专注与网站设计、网站建设H5场景定制、小程序制作等业务。10年已为伊金霍洛众多企业、政府机构等服务。创新互联专业网站建设公司优惠进行中。

Connection con=null;

PreparedStatement ps=null;

ResultSet rs=null;

String username=null;

try{

//实现数据连接池

Context ctx=new InitialContext();

ds=(DataSource)ctx.lookup("java:comp/env/jdbc/userInfo");

}catch(NamingException ne){ne.printStackTrace();}

try{

con=ds.getConnection();

String sql="select * from guestbook order by gst_time desc";

st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,

ResultSet.CONCUR_READ_ONLY);

rs=st.executeQuery(sql);

。。。。。。

。。。

}

在这段代码中

Context ctx=new InitialContext();

ds=(DataSource)ctx.lookup("java:comp/env/jdbc/userInfo");就是连接池代码。

它是读取配置文件(Context.xml)中数据的。

以下是配置文件:

Context path="/WebModule1" docBase="E:\Home\WebModule1" reloadable="true"

Resource name="jdbc/userInfo" auth="Container" type="javax.sql.DataSource"

maxActive="100" maxIdle="30" maxWait="10000" username="sa" password="bye0406"

driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"

url="jdbc:microsoft:sqlserver://localhost:1433;databasename=userInfo" /

/Context

path和docBase中的路径根据自己需要配置路径。该路径是WEB应用程序的路径。driverClassName和url是连接数据库的驱动类和连接的URL,是根据你使用的哪种数据库而定。

以下是四种数据库的配制驱动:

驱动

SQL Server 2000

类名:com.microsoft.jdbc.sqlserver.SQLServerDriver

URL:jdbc:microsoft:sqlserver://localhost:1433;databasename=pubs

Oracle

类名:oracle.jdbc.driver.OracleDriver

URL:jdbc:oracle:thin:@localhost:152:ORCL

Mysql

类名:com.mysql.jdbc.Driver

URL:jdbc:mysql://localhost:3306/databasename

JDBC-ODBC

类名:sun.jdbc.odbc.JdbcOdbcDriver

URL:jdbc:odbc:datasource_name;

典型Java线程池的代码及其各部分功能介绍

( )根据xml文件来管理线程池的最大最小线程数( )对线程池通过Timer定期扫描以防止线程未激活 ( )通过某一个变量(本程序中是freeThreadCount)来得到空闲线程的数目 一 配置xml(listen xml)是 ?xml version= encoding= UTF ?configConsumeThreadPoolminPools /minPools ! 线程池最小线程 maxPools /maxPools! 线程池最大线程 checkThreadPeriod /checkThreadPeriod ! 检查线程池中线程的周期 分钟 /ConsumeThreadPool/config 二 对于ConsumeThreadPoolPara的javabean: import java io *;public class ConsumeThreadPoolPara implements Serializable{private int minPools;private int maxPools;private int checkThreadPeriod;public int getMinPools(){return minPools;}public int getMaxPools(){return maxPools;}public int getCheckThreadPeriod(){return checkThreadPeriod;}public void setMinPools(int minPools){this minPools = minPools;}public void setMaxPools(int maxPools){this maxPools = maxPools;}public void setCheckThreadPeriod(int checkThreadPeriod){this checkThreadPeriod = checkThreadPeriod;}public String toString(){return minPools+ + maxPools+ +checkThreadPeriod;}public ConsumeThreadPoolPara() {}public static void main(String[] args) {ConsumeThreadPoolPara consumeThreadPool = new ConsumeThreadPoolPara();}} 三 解析xml程序代码(生成ConsumeThreadPoolPara) 使用jdom解析 import jdom *;import jdom input SAXBuilder;import java io *;import java util *;public class ParseConfig {static Hashtable Listens = null;static ConnPara connpara = null;static ConsumeThreadPoolPara consumeThreadPoolPara = null;private static String configxml = listen xml ;static{getConsumeThreadPoolPara(); //得到消费的线程池的参数}/*** 装载文档* @return 返回根结点* @throws JDOMException*/public static Element loadDocument() throws JDOMException{SAXBuilder parser = new SAXBuilder(); // 新建立构造器try {Document document = parser build(configxml);Element root = document getRootElement();return root;}catch(JDOMException e){logger error( listen xml文件格式非法! );throw new JDOMException();}}public static ConsumeThreadPoolPara getConsumeThreadPoolPara(){if(consumeThreadPoolPara ==null){try {Element root = loadDocument();Element consumeThreadPool = root getChild( ConsumeThreadPool );if (consumeThreadPool != null) { //代表有数据库配置consumeThreadPoolPara = new ConsumeThreadPoolPara();Element minPools = consumeThreadPool getChild( minPools );consumeThreadPoolPara setMinPools(Integer parseInt(minPools getTextTrim()));Element maxPools = consumeThreadPool getChild( maxPools );consumeThreadPoolPara setMaxPools(Integer parseInt(maxPools getTextTrim()));Element checkThreadPeriod = consumeThreadPool getChild( checkThreadPeriod );consumeThreadPoolPara setCheckThreadPeriod(Integer parseInt(checkThreadPeriod getTextTrim()));}}catch (JDOMException e) {}}return consumeThreadPoolPara;}} 四 线程池源代码 import java util *;/*** pTitle: 线程池/p* pDescription: 采集消费模块/p* pCopyright: Copyright (c) /p* pCompany: /p* @author 张荣斌* @version */public class ThreadPool {private static int minPools = ; //最小连接池数目private static int maxPools = ; //最大连接池数目private static int checkThreadPeriod = ; //检查连接池的周期ArrayList m_ThreadList; //工作线程列表LinkedList m_RunList = null; //工作任务列表int totalThread = ; //总线程数static int freeThreadCount = ; //未被使用的线程数目private java util Timer timer = null; //定时器static Object o = new Object();static{ //先初始化线程池的参数ConsumeThreadPoolPara consumeThreadPoolPara = ParseConfig getConsumeThreadPoolPara();if(consumeThreadPoolPara!=null){minPools = consumeThreadPoolPara getMinPools();maxPools = consumeThreadPoolPara getMaxPools();checkThreadPeriod = consumeThreadPoolPara getCheckThreadPeriod()* * ;}}public void setMinPools(int minPools){this minPools = minPools;}public void setMaxPools(int maxPools){this maxPools = maxPools;}public void setCheckThreadPeriod(int checkThreadPeriod){this checkThreadPeriod = checkThreadPeriod;}public ThreadPool() {m_ThreadList=new ArrayList();m_RunList=new LinkedList();for(int i= ;iminPools;i++){WorkerThread temp=new WorkerThread();totalThread = totalThread + ;m_ThreadList add(temp);temp start();try{Thread sleep( );}catch(Exception e){}}timer = new Timer(true); //启动定时器timer schedule(new CheckThreadTask(this) checkThreadPeriod);}/*** 当有一个工作来的时候启动线程池的线程* 当空闲线程数为 的时候 看总线程是否小于最大线程池的数目 就new一个新的线程 否则sleep 直到有空闲线程为止;* 当空闲线程不为 则将任务丢给空闲线程去完成* @param work*/public synchronized void run(String work){if (freeThreadCount == ) {if(totalThreadmaxPools){WorkerThread temp = new WorkerThread();totalThread = totalThread + ;m_ThreadList add(temp);temp start();synchronized(m_RunList){m_RunList add(work);m_RunList notify();}}else{while (freeThreadCount == ) {try {Thread sleep( );}catch (InterruptedException e) {}}synchronized(m_RunList){m_RunList add(work);m_RunList notify();}}} else {synchronized(m_RunList){m_RunList add(work);m_RunList notify();}}}/*** 检查所有的线程的有效性*/public synchronized void checkAllThreads() {Iterator lThreadIterator = erator();while (lThreadIterator hasNext()) { //逐个遍厉WorkerThread lTestThread = (WorkerThread) lThreadIterator next();if (! (lTestThread isAlive())) { //如果处在非活动状态时lTestThread = new WorkerThread(); //重新生成个线程lTestThread start(); //启动}}}/*** 打印调试信息*/public void printDebugInfo(){System out println( totalThread= +totalThread);System out println( m_ThreadList size()= +m_ThreadList size());}/**** pTitle: 工作线程类/p* @author 张荣斌* @version */class WorkerThread extends Thread{boolean running = true;String work;public void run(){while(running){synchronized(o){freeThreadCount++;}synchronized(m_RunList){while(m_RunList size() == ){try{m_RunList wait();if(!running) return;}catch(InterruptedException e){} lishixinzhi/Article/program/Java/gj/201311/27379

怎么在JAVA中创建一个数据库连接池?求实例代码

用c3po来创建数据库连接池,

1.到网络上下载c3p0-0.9.0.4.jar包,导入工程;(注意以下方法只能用于web服务).

2.找出web服务器中conf目录下的centent.xml,在里面加上以下配置

Resource auth="Container"

description="DB Connection"

driverClass="com.mysql.jdbc.Driver"

maxPoolSize="4"

minPoolSize="2"

acquireIncrement="1"

name="jdbc/TestDB"

user="root"

password="root"

factory="org.apache.naming.factory.BeanFactory"

type="com.mchange.v2.c3p0.ComboPooledDataSource"

jdbcUrl="jdbc:mysql://localhost:3306/自己的数据库名?autoReconnect=true" /

3.java获取连接池的代码;

import java.sql.Connection;

import java.sql.SQLException;

import javax.naming.InitialContext;

import javax.naming.NamingException;

import javax.sql.DataSource;

public class DBUtils {

static InitialContext ic;

static DataSource ds;

static{

try {

ic = new InitialContext();

ds = (DataSource)ic.lookup("java:comp/env/jdbc/TestDB");

} catch (NamingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public static Connection getCon() {

try {

return ds.getConnection();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

return null;

}

}

}

通过以上代码,即可获取连接池中的连接.


当前名称:java链接池的代码 java连接池druid
浏览路径:http://mswzjz.cn/article/ddoopch.html

其他资讯