search
HomeDatabaseMysql Tutorialmysql数据库连接池配置教程_MySQL

bitsCN.com 第一步:写javabean

package withouttears.jdbc.db;
import java.util.HashMap;
import java.sql.*;
//JNDI有两个核心接口Context和DirContext,
//Context中包含了基本的名字操作,而DirContext则将这些操作扩展到目录服务。
import javax.naming.Context;
import javax.naming.InitialContext;
//数据库资源的连接工厂是javax.sql.DataSource对象,
//它可以创建java.sql.Connection数据库连接对象。
import javax.sql.DataSource;
//目前您可以从Java开发者连接(http://java.sun.com/products/jdbc/download.html#rowsetcobundle1_0)
//下载CachedRowSet的实现。下载并解压缩安装文件后,将"rowset.jar"文件放到您的类目录下。
//CachedRowSet在sun.jdbc.rowset包中。
import sun.jdbc.rowset.CachedRowSet;
/**
* 作者:wiThouTTears
* 时间:2006-12-13
* */
public class Database {
/**************************************************************/
/* 函数:localhost
* 功能:建立连接池
* */
private static DataSource localhost(){
DataSource ds=null;
//在HashMap中通过get()来获取value,通过put()来插入value,
//ContainsKey()则用来检验对象是否已经存在
HashMap cachedDs=new HashMap ();
if(cachedDs.containsKey("ds"))//取出空闲状态的数据库连接
{
/* 在DataSource中事先建立了多个数据库连接,
* 这些数据库连接保存在连接池(Connect Pool)中。
* Java程序访问数据库时,只需要从连接池中取出空闲状态的数据库连接;
* 当程序访问数据库结束,再将数据库连接放回连接池。
* */
ds = (DataSource)cachedDs.get("ds");
}
else
try
{
/*在javax.naming包中提供了Context接口,
* 该接口提供了将对象和名字绑定,以及通过名字检索对象的方法。
* */
Context initCtx = new InitialContext();
//lookup(String name):返回与指定的名字绑定的对象,获得数据库连接工厂
ds = (DataSource)initCtx.lookup("java:comp/env/jdbc/testdb");
cachedDs.put("ds", ds);
}
catch(Exception e)
{
e.printStackTrace();
}
return ds;
}
/**************************************************************/
/* 函数:getConnection
* 功能:库的连接
* */
private static Connection getConnection(){
Connection conn = null;
try
{
DataSource ds = localhost();
conn = ds.getConnection();
}
catch(Exception e)
{
e.printStackTrace();
}
return conn;
}
/**************************************************************/
/* 函数:close
* 功能:关闭连接
* */
private static void close(Connection conn)
{
try
{
if(conn != null)
conn.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
/**************************************************************/
/* 函数:executeQuery
* 功能:数据查询
* */
public static CachedRowSet executeQuery(String sql)
{
Connection conn=null;
CachedRowSet rs=null;
try{
rs=new CachedRowSet();
conn=getConnection();
Statement stmt=conn.createStatement();
ResultSet rs1=stmt.executeQuery(sql);
rs.populate(rs1);
}
catch(Exception e)
{
//System.out.println(e.toString());
}
finally{
try
{
conn.close();
}
catch(Exception ex)
{}
} return rs;
}
/**************************************************************/
/* 函数:executeUpdate
* 功能:数据更新(添加/更改/删除)
* */
public static boolean executeUpdate(String sql)
{
boolean bl;
bl = false;
Connection conn = getConnection();
try
{
Statement stmt = conn.createStatement();
if(stmt.executeUpdate(sql) > 0)
stmt.close();
bl = true;
}
catch(SQLException e)
{
}
finally
{
close(conn);
}
return bl;
}
/**************************************************************/
}

编译得到withouttears/db/Database.class并放到E:/MyWorkSpace/test/WEB-INF/classes下,即E:/MyWorkSpace/test/WEB-INF/classes/withouttears/db/Database.class,注意别弄错了。
第二步:配置Tomcat(我用是Tomcat 5.5.7)
1. 在C:/Program Files/Tomcat 5.5.7/conf/Catalina/localhost下新建一个test.xml,内容如下:
注:docBase为你的web文件所在地,我用的是E:/MyWorkSpace/test。path可写可不写,但在Linux下必须写上,Windows下不写我测试可以用,最好写上。这里的test.xml指定的文件夹不像我们平时用的那样在C:/Program Files/Tomcat 5.5.7/webapps/test,不过目的一样都是表示用http://localhost:8080/test/来访问,相当于IIS下的虚拟目录,可以是任意的。
2. 在C:/Program Files/Tomcat 5.5.7/conf/下建立context.xml,在E:/MyWorkSpace/test下新建WEB-INF/web.xml。
context.xml




WEB-INF/web.xml
META-INF/context.xml


auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/mytestdb"
username="root"
password="157744375"
maxActive="100"
maxIdle="30"
maxWait="10000"
/>


注: 链接池配置文件,这样我们就可以用第一步写的Javabean类Database中的localhost()函数来读取这个content.xml中的jdbc/testdb名称
web.xml




test


test.jsp





注: web.xml放web的默认主页(如:test.jsp或者index.jsp)和程序中要用到servlet的映射,不管它我们这里用不到。
第三步:写test.jsp








Insert title


String sql=null;
sql="select * from table_test";
ResultSet rs=Database.executeQuery(sql);
try{
while(rs.next()){
%>
濮撳悕锛

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

How to use MySQL functions for data processing and calculationHow to use MySQL functions for data processing and calculationApr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

An efficient way to batch insert data in MySQLAn efficient way to batch insert data in MySQLApr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

Steps to add and delete fields to MySQL tablesSteps to add and delete fields to MySQL tablesApr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor