mysqljava数据库连接池
连接先建立一些连接,并且这些连接允许共享,因此这样就节省了每次连接的时间开销。Mysql数据库为例,连接池在Tomcat中的配置与使用。
1、创建数据库Student,表student
2、配置server.xml文件。Tomcat安装目录下conf中server.xml文件。
<GlobalNamingResources>
<Resource
name="jdbc/DBPool"
type="javax.sql.DataSource"
password=""
driverClassName="com.mysql.jdbc.Driver"
maxIdle="2"
maxWait="5000"
username="root"
url="jdbc:mysql://localhost:3306/student"
maxActive="3"
/>
</GlobalNamingResources>
name:指定连接池的名称
type:指定连接池的类,他负责连接池的事务处理
url:指定要连接的数据库
driverClassName:指定连接数据库使用的驱动程序
username:数据库用户名
password:数据库密码
maxWait:指定最大建立连接等待时间,如果超过此时间将接到异常
maxIdle:指定连接池中连接的最大空闲数
maxActive:指定连接池最大连接数
3、配置web.xml文件。
<web-app>
<resource-ref>
<description>mysql数据库连接池配置</description>
<res-ref-name>jdbc/DBPool</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
</web-app>
4、配置context.xml文件
与server.xml文件所在的位置相同。
<Context>
<ResourceLink
name="jdbc/DBPool"
type="javax.sql.DataSource"
global="jdbc/DBPool"
/>
</Context>
5、测试
DataSource pool = null;
Context env = null;
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try{
env = (Context)new InitialContext().lookup("java:comp/env");
//检索指定的对象,返回此上下文的一个新实例
pool = (DataSource)env.lookup("jdbc/DBPool");
//获得数据库连接池
if(pool==null){out.printl("找不到指定的连接池!");}
con = pool.getConnection();
st = con.createStatement();
rs = st.executeQuery("select * from student");
}catch(Exception ex){out.printl(ne.toString());}
Ⅱ 请问用java如何连接mysql数据库 mysql server版本为 5.5.22 驱动包版本为5.1.18
拷过来的,你看看吧,我就是按这个做的。
Java连接数据库过程:
第一步:驱动安装和路径设置Step1:到mysql的官方网站下载mysql-connector-java-5.1.18.zip驱动,解压以后复制里面的mysql-connector-java-5.1.18.jar到jdk安装目录的lib文件夹中;Step2:设置环境变量CLASSPATH=.;%JAVA_HOME%\lib\mysql-connector-java-5.1.18.jar;
第二步:程序编写
Step1:在程序中加载并注册JDBC驱动器,其中JDBC-ODBC在JDK自带,默认已经注册,所以不需要注册;
Class.forName(“com.mysql.jdbc.Driver”);
java.sql.DriverManager.registerDriver(newcom.mysql.jdbc.Driver()); //对于MySQL不是必须
Step2:建立与数据库的连接
Connection con =java.sql.DriverManager.getConnection(dburl,user,pwd);
dburl表示连接数据库的JDBC URL: jdbc:mysql://localhost:3306/DB_NAME
user: 数据库用户名
pwd:数据库密码
Step3:创建Statement对象,准备执行SQL语句
Statement stmt = con.createStatement();
Step4: 执行SQL语句
String sql = “select * from tb_name”;
ResultSet rs = stmt.executeQuery(sql);
Step5:遍历ResultSet对象中的记录
while(rs.next()){
String name = rs.getString(index);
Long id = rs.getLong(index);
Int age = rs.getInt(index);
}
Step6:关闭数据库
rs.close();
stmt.close();
con.close();
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/yaoxy/archive/2009/08/06/4418116.aspx
Ⅲ java数据库连接池最大连接数最小连接数怎么设置
最大连接数:这个连接池最多能有几条连接,如果初始化的连接数没有了,用户可以创建,但是要给个判断不能超过最大连接数。
最小连接数:就是连接池初始化的连接(连接池初始化多少条连接)
// 设置最大连接数,(根据并发请求合理设置)。
config.setMaxTotal(100);
// 设置最大空闲连接数,(根据并发请求合理设置)
config.setMaxIdle(20);
// 多长空闲时间之后回收空闲连接
setMinEvictableIdleTimeMillis(60000);
// 设置最小空闲连接数或者说初始化连接数
config.setMinIdle(10);
// 设置最大等待时间
config.setMaxWaitMillis(500);
// 跟验证有关
config.setTestOnBorrow(true);
// 跟验证有关
config.setTestOnReturn(false);
// 启动空闲连接的测试
config.setTestWhileIdle(false);
Ⅳ java怎么连接mysql数据库
这里介绍两种方式:
一,jdbc链接MySQL数据库:
1,如果你用jdbc方式,则按照下列方式进行连接:
A,注册驱动
B,链接数据库
C,执行sql
D,返回结果集
如下为一个基本完整流程:
packagecom.hu.demo;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
importjava.sql.SQLException;
publicclassDBHelper{
publicstaticfinalStringurl="jdbc:mysql://127.0.0.1/student";
publicstaticfinalStringname="com.mysql.jdbc.Driver";
publicstaticfinalStringuser="root";
="root";
publicConnectionconn=null;
publicPreparedStatementpst=null;
publicDBHelper(Stringsql){
try{
Class.forName(name);//指定连接类型
conn=DriverManager.getConnection(url,user,password);//获取连接
pst=conn.prepareStatement(sql);//准备执行语句
}catch(Exceptione){
e.printStackTrace();
}
}
publicvoidclose(){
try{
this.conn.close();
this.pst.close();
}catch(SQLExceptione){
e.printStackTrace();
}
}
}
2,将注册,链接封装好,执行sql语句,返回结果集,代码如下:
packagecom.hu.demo;
importjava.sql.ResultSet;
importjava.sql.SQLException;
publicclassDemo{
staticStringsql=null;
staticDBHelperdb1=null;
staticResultSetret=null;
publicstaticvoidmain(String[]args){
sql="select*fromstuinfo";//SQL语句
db1=newDBHelper(sql);//创建DBHelper对象
try{
ret=db1.pst.executeQuery();//执行语句,得到结果集
while(ret.next()){
Stringuid=ret.getString(1);
Stringufname=ret.getString(2);
Stringulname=ret.getString(3);
Stringudate=ret.getString(4);
System.out.println(uid+" "+ufname+" "+ulname+" "+udate);
}//显示数据
ret.close();
db1.close();//关闭连接
}catch(SQLExceptione){
e.printStackTrace();
}
}
}
3,查询结果如下:
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
<!--配置数据源-->
<beanname="dataSource"class="com.alibaba.druid.pool.DruidDataSource"
init-method="init"destroy-method="close">
<propertyname="url"value="${jdbc_url}"/>
<propertyname="username"value="${jdbc_username}"/>
<propertyname="password"value="${jdbc_password}"/>
<!--初始化连接大小-->
<propertyname="initialSize"value="0"/>
<!--连接池最大使用连接数量-->
<propertyname="maxActive"value="20"/>
<!--连接池最小空闲-->
<propertyname="minIdle"value="0"/>
<!--获取连接最大等待时间-->
<propertyname="maxWait"value="60000"/>
<!--<propertyname="poolPreparedStatements"value="true"/><property
name=""value="33"/>-->
<propertyname="validationQuery"value="${validationQuery}"/>
<propertyname="testOnBorrow"value="false"/>
<propertyname="testOnReturn"value="false"/>
<propertyname="testWhileIdle"value="true"/>
<!--配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒-->
<propertyname="timeBetweenEvictionRunsMillis"value="60000"/>
<!--配置一个连接在池中最小生存的时间,单位是毫秒-->
<propertyname="minEvictableIdleTimeMillis"value="25200000"/>
<!--打开removeAbandoned功能-->
<propertyname="removeAbandoned"value="true"/>
<!--1800秒,也就是30分钟-->
<propertyname="removeAbandonedTimeout"value="1800"/>
<!--关闭abanded连接时输出错误日志-->
<propertyname="logAbandoned"value="true"/>
<!--监控数据库-->
<!--<propertyname="filters"value="stat"/>-->
<propertyname="filters"value="mergeStat"/>
</bean>
<!--myBatis文件-->
<beanid="sqlSessionFactory"class="org.mybatis.spring.SqlSessionFactoryBean">
<propertyname="dataSource"ref="dataSource"/>
<!--自动扫描entity目录,省掉Configuration.xml里的手工配置-->
<propertyname="mapperLocations"value="classpath:com/fourfaith/*/mapping/*.xml"/>
</bean>
<beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer">
<propertyname="basePackage"value="com.fourfaith.**."/>
<propertyname="sqlSessionFactoryBeanName"value="sqlSessionFactory"/>
</bean>
<!--配置事务管理器-->
<beanid="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<propertyname="dataSource"ref="dataSource"/>
</bean>
<!--拦截器方式配置事物-->
<tx:adviceid="transactionAdvice"transaction-manager="transactionManager">
<tx:attributes>
<tx:methodname="add*"propagation="REQUIRED"/>
<tx:methodname="append*"propagation="REQUIRED"/>
<tx:methodname="insert*"propagation="REQUIRED"/>
<tx:methodname="save*"propagation="REQUIRED"/>
<tx:methodname="update*"propagation="REQUIRED"/>
<tx:methodname="modify*"propagation="REQUIRED"/>
<tx:methodname="edit*"propagation="REQUIRED"/>
<tx:methodname="delete*"propagation="REQUIRED"/>
<tx:methodname="remove*"propagation="REQUIRED"/>
<tx:methodname="repair"propagation="REQUIRED"/>
<tx:methodname="delAndRepair"propagation="REQUIRED"/>
<tx:methodname="import*"propagation="REQUIRED"read-only="false"
rollback-for="java.lang.Exception"/>
<tx:methodname="get*"propagation="SUPPORTS"/>
<tx:methodname="find*"propagation="SUPPORTS"/>
<tx:methodname="load*"propagation="SUPPORTS"/>
<tx:methodname="search*"propagation="SUPPORTS"/>
<tx:methodname="datagrid*"propagation="SUPPORTS"/>
<tx:methodname="*"propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcutid="transactionPointcut"
expression="execution(*com...*.service..*Impl.*(..))"/>
<aop:advisorpointcut-ref="transactionPointcut"
advice-ref="transactionAdvice"/>
</aop:config>
<!--配置druid监控springjdbc-->
<beanid="druid-stat-interceptor"
class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">
</bean>
<beanid="druid-stat-pointcut"class="org.springframework.aop.support.JdkRegexpMethodPointcut"
scope="prototype">
<propertyname="patterns">
<list>
<value>com...*.service.*</value>
</list>
</property>
</bean>
<aop:config>
<aop:advisoradvice-ref="druid-stat-interceptor"
pointcut-ref="druid-stat-pointcut"/>
</aop:config>
</beans>
还有很多方式可以实现,这里就简略的描述一番。
Ⅳ java用mysql数据库连接池是总是加载不到驱动Cannot load JDBC driver class 'com.MySQL.jdbc.Driver'。
打开开发工具的window->show View->DBbrowser 在里面面板点右键 New 然后选MySQL 给他数据库用户名和密码,然后指定驱动的引用和路径,然后测试连接
Ⅵ eclipse和mysql怎么连接
1.在新建的Project中右键新建Floder
2.创建名为lib的包
3.接下来解压你下载的mysql的jar包,拷贝其中的.jar文件
4.在工程lib包下邮件 选择paste即粘贴,把mysql的jar包拷贝进来
5.在mysql的jar包上右键选择 build path - add to build path
6.添加完毕之后,工程才与Mysql的jar包关联起来,现在可以使用相关类和方法了
7.在工程中新建JdbcTest1.java类
8.连接MySQL数据库驱动或使用连接池
9.在java类中准备连接数据库的基本信息
Ⅶ Java开发常用的几个数据库连接池
数据库连接池的好处是不言而喻的,现在大部分的application
server都提供自己的数据库连接池方案,此时,只要按照application server的文档说明,正确配置,即可在应用中享受到数据库连接池的好处。
但是,有些时候,我们的应用是个独立的java
application,并不是普通的WEB/J2EE应用,而且是单独运行的,不要什么application
server的配合,这种情况下,我们就需要建立自己的数据库连接池方案了。
1、 DBCP
DBCP是Apache的一个开源项目:
commons.dbcp
DBCP依赖Apache的另外2个开源项目
commons.collections和commons.pool
dbcp包,目前版本是1.2.1:http://jakarta.apache.org/commons/dbcp/
pool包,目前版本是1.3:http://jakarta.apache.org/commons/pool/,
common-collections包:http://jakarta.apache.org/commons/collections/
下载这些包并将这些包的路径添加到classpath中就可以使用dbcp做为项目中的数据库连接池使用了。
在建立我们自己的数据库连接池时,可以使用xml文件来传入需要的参数,这里只使用hard
code的方式来简单介绍,所有需要我们自己写的代码很少,只要建立一个文件如下:
import
org.apache.commons.dbcp.BasicDataSource;
import
org.apache.commons.dbcp.BasicDataSourceFactory;
import
java.sql.SQLException;
import java.sql.Connection;
import
java.util.Properties;
public class ConnectionSource {
private static BasicDataSource dataSource =
null;
public ConnectionSource() {
}
public static void init() {
if (dataSource != null) {
try
{
dataSource.close();
} catch (Exception e)
{
}
dataSource = null;
}
try {
Properties p = new
Properties();
p.setProperty("driverClassName",
"oracle.jdbc.driver.OracleDriver");
p.setProperty("url",
"jdbc:oracle:thin:@192.168.0.1:1521:testDB");
p.setProperty("password", "scott");
p.setProperty("username",
"tiger");
p.setProperty("maxActive", "30");
p.setProperty("maxIdle", "10");
p.setProperty("maxWait",
"1000");
p.setProperty("removeAbandoned",
"false");
p.setProperty("removeAbandonedTimeout",
"120");
p.setProperty("testOnBorrow", "true");
p.setProperty("logAbandoned", "true");
dataSource = (BasicDataSource)
BasicDataSourceFactory.createDataSource(p);
} catch (Exception e) {
}
}
public static synchronized Connection
getConnection() throws SQLException {
if (dataSource == null) {
init();
}
Connection conn = null;
if (dataSource != null) {
conn = dataSource.getConnection();
}
return conn;
}
}
接下来,在我们的应用中,只要简单地使用ConnectionSource.getConnection()就可以取得连接池中的数据库连接,享受数据库连接带给我们的好处了。当我们使用完取得的数据库连接后,只要简单地使用connection.close()就可把此连接返回到连接池中,至于为什么不是直接关闭此连接,而是返回给连接池,这是因为dbcp使用委派模型来实现Connection接口了。
在使用Properties来创建BasicDataSource时,有很多参数可以设置,比较重要的还有:
testOnBorrow、testOnReturn、testWhileIdle,他们的意思是当是取得连接、返回连接或连接空闲时是否进行有效性验证(即是否还和数据库连通的),默认都为false。所以当数据库连接因为某种原因断掉后,再从连接池中取得的连接,实际上可能是无效的连接了,所以,为了确保取得的连接是有效的,
可以把把这些属性设为true。当进行校验时,需要另一个参数:validationQuery,对oracle来说,可以是:SELECT COUNT(*) FROM
DUAL,实际上就是个简单的SQL语句,验证时,就是把这个SQL语句在数据库上跑一下而已,如果连接正常的,当然就有结果返回了。
还有2个参数:timeBetweenEvictionRunsMillis 和
minEvictableIdleTimeMillis,
他们两个配合,可以持续更新连接池中的连接对象,当timeBetweenEvictionRunsMillis
大于0时,每过timeBetweenEvictionRunsMillis
时间,就会启动一个线程,校验连接池中闲置时间超过minEvictableIdleTimeMillis的连接对象。
还有其他的一些参数,可以参考源代码。
2、
C3P0:
C3P0是一个开放源代码的JDBC连接池,C3PO
连接池是一个优秀的连接池,推荐使用。C3PO实现了JDBC3.0规范的部分功能,因而性能更加突出,包括了实现jdbc3和jdbc2扩展规范说明的Connection 和Statement 池的DataSources 对象。
下载地址:http://sourceforge.net/projects/c3p0
package
com.systex.utils.web;
import java.beans.PropertyVetoException;
import
java.sql.Connection;
import java.sql.SQLException;
import
javax.sql.DataSource;
import
com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3PODataSource {
private static
ComboPooledDataSource dataSource = null;
private static final String driver
= "com.mysql.jdbc.Driver";
private static final String url =
"jdbc:mysql://localhost:3306/wyd";
private static final String userName =
"root";
private static final String password = "root";
public static DataSource getDataSource() {
if
(dataSource == null) {
dataSource = new ComboPooledDataSource();
try
{
dataSource.setDriverClass(driver);
} catch (PropertyVetoException
e) {
System.out.println("DataSource Load Driver
Exception!!");
e.printStackTrace();
}
dataSource.setJdbcUrl(url);
dataSource.setUser(userName);
dataSource.setPassword(password);
//
设置连接池最大连接容量
dataSource.setMaxPoolSize(20);
//
设置连接池最小连接容量
dataSource.setMinPoolSize(2);
//
设置连接池最大statements对象容量
dataSource.setMaxStatements(100);
}
return
dataSource;
}
public static Connection getConnection() throws
SQLException {
return
C3PODataSource.getDataSource().getConnection();
}
}
3、 Proxool
这是一个Java SQL
Driver驱动程序,提供了对你选择的其它类型的驱动程序的连接池封装。可以非常简单的移植到现存的代码中。完全可配置。快速,成熟,健壮。可以透明地为你现存的JDBC驱动程序增加连接池功能。
官方网站: http://proxool.sourceforge.net/
下载地址:http://proxool.sourceforge.net/download.html
Ⅷ java线程中使用mysql连接查询数据库
不建议这样做,一般不符合开发规范,如果这样的话,你想想在业务量多的情况下,多个线程如果不控制,数据库连接会将数据库服务器爆掉的,会影响业务的
常规做法:数据库连接池(rid了解一下),据某些统计哈,真正用来做查询的资源不超过整个查询数据库的生命周期的30%,大部分时间都用开创建连接关闭连接等操作,如果这个时候建立数据库连接池的话,可以有效的将这部分时间释放掉