配置項(xiàng)目我用的是手工的方式配置的,不知道在Myeclipse中能不能用自動(dòng)配置的方式配置。在Tomcat配置項(xiàng)目添加在server.xml中添加一句話就可以了
<Context path="/c3p0" docBase="C:\Documents and Settings\Administrator\Workspaces\MyEclipse 8.5\c3p0/WebRoot" debug="0" privileged="true" reloadable="true">
那么接下來(lái)就配置Tomcat下conf中的congtent.xml文件
<Resource name="jdbc/c3p0" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="1000" username="root" password="xiaoyang"
driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://127.0.0.1:3306/test"
removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true"/>
然后再就可以用用java代碼就能直接使用了
package com.yangtao.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBConnection {
private Connection conn = null;
public Connection getConnection() {
// 生成上下文對(duì)象,通過(guò)它可以向容器發(fā)送別名.
Context context;
try {
context = new InitialContext();
// 查找對(duì)象
DataSource ds = (DataSource) context
.lookup("java:comp/env/jdbc/c3p0");// jdbc/liuwei為配置文件中的name
// 得到連接
try {
conn = ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public List<Integer> getAllID() throws SQLException {
List<Integer> list = new ArrayList<Integer>();
DBConnection dbConnection = new DBConnection();
Connection connection = dbConnection.getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from reply");
while(resultSet.next()){
int id = resultSet.getInt(1);
//System.out.println(id);
list.add(id);
}
if(resultSet != null){
resultSet.close();
}
if(statement != null){
statement.close();
}
if(connection != null){
connection.close();
}
return list;
}
}
DAO層可以負(fù)責(zé)java增刪改查之類的,然后再頁(yè)面就可以直接使用了
不能直接寫成main()方法來(lái)測(cè)試,測(cè)試會(huì)提示錯(cuò)誤的。
基本這樣配置就可以了,不過(guò)有個(gè)問(wèn)題,就是在關(guān)閉Tomcat服務(wù)器的時(shí)候 下面會(huì)說(shuō)有可能造成內(nèi)存泄露 不知道這個(gè)是什么原因。還望高手指導(dǎo)!!!