/*****************************
* 数据库连接 bean ,用来连接 resin 的连接池
*****************************/
package net.asales.mysql;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
public class DBConnection {
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
private int resultNum = 0;
/**
* 构造函数
* 找到数据源,并用这个数据源创建连接
*/
public DBConnection() {
try {
Context env = new InitialContext();
DataSource pool = (DataSource) env.lookup("java:comp/env/jdbc/asales");
if (pool == null)
throw new Exception("jdbc/asales is an unknown DataSource");
conn = pool.getConnection();
stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("naming:" + e.getMessage());
}
}
/**
* 执行SQL语句:查询记录
* @param sql SQL语句
* @return ResultSet 记录集
*/
public ResultSet executeQuery(String sql) {
rs = null;
try {
rs = stmt.executeQuery(sql);
} catch(SQLException se) {
System.out.println("Query error:" + se.getMessage());
}
return rs;
}
/**
* 执行SQL语句 :插入与更新记录
* @param sql SQL语句
* @return int resultNum 更新的记录数
*/
public int executeUpdate(String sql) {
resultNum=0;
try {
resultNum = stmt.executeUpdate(sql);
} catch (SQLException se) {
System.err.println("Update error:" + se.getMessage());
}
return resultNum;
}
/**
* 关闭连接
*/
public void close() {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException se) {
System.out.println("close error: " + se.getMessage());
}
}
}
===================
以下是RESIN配置文件中关于数据源的配置例:
<resource-ref>
<res-ref-name>jdbc/asales</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<init-param driver-name="org.gjt.mm.mysql.Driver"/>
<init-param url="jdbc:mysql://localhost:3306/asales"/>
<init-param user="root"/>
<init-param password=""/>
<init-param max-connections="20"/>
<init-param max-idle-time="30"/>
</resource-ref>
查看本文来源