配置Tomcat7 Sqlserver连接池。

配置Tomcat7 Sqlserver连接池。,第1张

请参考

首先配置:META-INF/context.xml:

<?xml version="1.0" encoding="UTF-8"?>

<Context path="" reloadable="true" crossContext="true">

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

maxActive="100" maxIdle="30" maxWait="10000" username="root" password="root"

driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://127.0.0.1:3306/db_name" />

</Context>

再配置:WEB-INF/web.xml:在web-app元素下

<resource-ref>

<description>DB Connection</description>

<res-ref-name>jdbc/TestDB</res-ref-name>

<res-type>javax.sql.DataSource</res-type>

<res-auth>Container</res-auth>

</resource-ref>

程序:

InitialContext ctx = new InitialContext()

Context envContext = (Context) ctx.lookup("java:comp/env")

DataSource ds = (DataSource) envContext.lookup("jdbc/TestDB")

Connection conn = ds.getConnection()

Statement stmt = conn.createStatement()

stmt.execute(“执行的SQL语句”)

stmt.close()

conn.close()

java连接SqlServer2008的数据库连接池使用:

import java.sql.Connection

import java.sql.SQLException

import java.util.Vector

/**数据库连接池的公共类 **/

public class ConnectionPool {

private Vector<Connection>pool//声明集合,里面只能是放Connection

/**

* 声明要的东西

*/

private String url = "jdbc:sqlserver://localhost:1433database=ajax"

private String username = "sa"

private String password = "sa123"

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

/**

* 连接池的大小,也就是连接池中有多少个数据库连接

*/

private int poolSize = 5

private static ConnectionPool instance = null

/**

* 私有的构造方法,禁止外部创建本类的对象,要想获得本类的对象,通过<code>getIstance</code>方法

* 使用了设计模式中的单子模式

*/

private ConnectionPool() {

init()

}

/**

* 连接池初始化方法,读取属性文件的内容 建立连接池中的初始连

*/

private void init() {

pool = new Vector<Connection>(poolSize)

//readConfig()

addConnection()

}

/**

* 返回连接到连接池

*/

public synchronized void release(Connection conn) {

pool.add(conn)

}

/**

* 关闭连接池中的所有数据库连接

*/

public synchronized void closePool() {

for (int i = 0i <pool.size()i++) {

try {

((Connection) pool.get(i)).close()

} catch (SQLException e) {

e.printStackTrace()

}

pool.remove(i)

}

}

/**

* 返回当前连接池的对象

*/

public static ConnectionPool getInstance() {

if (instance == null) {

instance = new ConnectionPool()

}

return instance

}

/**

* 返回连接池中的一个数据库连接

*/

public synchronized Connection getConnection() {

if (pool.size() >0) {

Connection conn = pool.get(0)

pool.remove(conn)

return conn

} else {

return null

}

}

/**

* 在连接池中创建初始设置的的数据库连接

*/

private void addConnection() {

Connection conn = null

for (int i = 0i <poolSizei++) {

try {

Class.forName(driverClassName)

conn = java.sql.DriverManager.getConnection(url, username,

password)

pool.add(conn)

} catch (ClassNotFoundException e) {

e.printStackTrace()

} catch (SQLException e) {

e.printStackTrace()

}

}

}

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/9886234.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-03
下一篇 2023-05-03

发表评论

登录后才能评论

评论列表(0条)

保存