當前位置:首頁 » 操作系統 » mysqljava資料庫連接池

mysqljava資料庫連接池

發布時間: 2022-10-29 05:27:13

java資料庫連接池的幾種配置方法(以Mysql

連接先建立一些連接,並且這些連接允許共享,因此這樣就節省了每次連接的時間開銷。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%,大部分時間都用開創建連接關閉連接等操作,如果這個時候建立資料庫連接池的話,可以有效的將這部分時間釋放掉

熱點內容
解壓美食蛋糕 發布:2025-05-13 23:36:25 瀏覽:353
php含有字元 發布:2025-05-13 23:32:08 瀏覽:183
如何找出蘋果手機已連接wifi密碼 發布:2025-05-13 23:22:52 瀏覽:263
ie10緩存 發布:2025-05-13 23:10:09 瀏覽:458
安卓手機圖標怎麼設置提示 發布:2025-05-13 23:07:56 瀏覽:809
香蕉FTP下載 發布:2025-05-13 23:07:11 瀏覽:940
for循環sql語句 發布:2025-05-13 22:45:49 瀏覽:19
python實用代碼 發布:2025-05-13 22:19:41 瀏覽:843
dede資料庫的配置文件 發布:2025-05-13 22:19:08 瀏覽:970
給字元加密 發布:2025-05-13 22:12:32 瀏覽:975