当前页面: 开发资料首页 → JSP 专题 → Servlet开发中JDBC的高级应用
摘要: Servlet开发中JDBC的高级应用
连结数据库
JDBC使用数据库URL来说明数据库驱动程序。数据库URL类似于通用的URL,但SUN 在定义时作了一点简化,其语法如下:
Jdbc::[node]/[database]
其中子协议(subprotocal)定义驱动程序类型,node提供网络数据库的位置和端口号,后面跟可选的参数。例如:
String url=”jdbc:inetdae:myserver:1433?language=us-english&sql7=true”
表示采用inetdae驱动程序连接1433端口上的myserver数据库服务器,选择语言为美国英语,数据库的版本是mssql server 7.0。Class.forName(“”);
或Class.forName(“”).newInstance();
然后,DriverManager创建一个特定的连接:Connection connection=DriverManager.getConnection(url,login,password);
Statement stmt=connection.createStatement();
Statement具有各种方法(API),如executeQuery,execute等可以返回查询的结果集。结果集是一个ResultSet对象。具体的可以通过jdbc开发文档查看。可以sun的站点上下载import java.sql.*; // 输入JDBC package
String url = "jdbc:inetdae:myserver:1433";// 主机名和端口
String login = "user";// 登录名
String password = "";// 密码
try {
DriverManager.setLogStream(System.out); file://为显示一些的信息打开一个流
file://调用驱动程序,其名字为com.inet.tds.TdsDriver
file://Class.forName("com.inet.tds.TdsDriver");
file://设置超时
DriverManager.setLoginTimeout(10);
file://打开一个连接
Connection connection = DriverManager.getConnection(url,login,password);
file://得到数据库驱动程序版本
DatabaseMetaData conMD = connection.getMetaData();
System.out.println("Driver Name:\t" + conMD.getDriverName());
System.out.println("Driver Version:\t" + conMD.getDriverVersion());
file://选择数据库
connection.setCatalog( "MyDatabase");
file://创建Statement
Statement st = connection.createStatement();
file://执行查询
ResultSet rs = st.executeQuery("SELECT * FROM mytable");
file://取得结果,输出到屏幕
while (rs.next()){
for(int j=1; j<=rs.getMetaData().getColumnCount(); j++){
System.out.print( rs.getObject(j)+"\t");
}
System.out.println();
}
file://关闭对象
st.close();
connection.close();
} catch(Exception e) {
e.printStackTrace();
}
public DBConnectionPool(String name, String URL, String user,
String password, int maxConn) {
this.name = name;
this.URL = URL;
this.user = user;
this.password = password;
this.maxConn = maxConn;
}
public synchronized Connection getConnection() {
Connection con = null;
if (freeConnections.size() > 0) {
// Pick the first Connection in the Vector
// to get round-robin usage
con = (Connection) freeConnections.firstElement();
freeConnections.removeElementAt(0);
try {
if (con.isClosed()) {
log("Removed bad connection from " + name);
// Try again recursively
con = getConnection();
}
}
catch (SQLException e) {
log("Removed bad connection from " + name);
// Try again recursively
con = getConnection();
}
}
else if (maxConn == 0 || checkedOut < maxConn) {
con = newConnection();
}
if (con != null) {
checkedOut++;
}
return con;
}
private Connection newConnection() {
Connection con = null;
try {
if (user == null) {
con = DriverManager.getConnection(URL);
}
else {
con = DriverManager.getConnection(URL, user, password);
}
log("Created a new connection in pool " + name);
}
catch (SQLException e) {
log(e, "Can not create a new connection for " + URL);
return null;
}
return con;
}
public synchronized Connection getConnection(long timeout) {
long startTime = new Date().getTime();
Connection con;
while ((con = getConnection()) == null) {
try {
wait(timeout);
}
catch (InterruptedException e) {}
if ((new Date().getTime() - startTime) >= timeout) {
// Timeout has expired
return null;
}
}
return con;
}
public synchronized void freeConnection(Connection con) {
// Put the connection at the end of the Vector
freeConnections.addElement(con);
checkedOut--;
notifyAll();
}
public synchronized void release() {
Enumeration allConnections = freeConnections.elements();
while (allConnections.hasMoreElements()) {
Connection con = (Connection) allConnections.nextElement();
try {
con.close();
log("Closed connection for pool " + name);
}
catch (SQLException e) {
log(e, "Can not close connection for pool " + name);
}
}
freeConnections.removeAllElements();
}
private DBConnectionManager() {
init();
}
static synchronized public DBConnectionManager getInstance() {
if (instance == null) {
instance = new DBConnectionManager();
}
clients++;
return instance;
}
private void init() {
InputStream is = getClass().getResourceAsStream("/db.properties");
Properties dbProps = new Properties();
try {
dbProps.load(is);
}
catch (Exception e) {
System.err.println("Can not read the properties file. " + "Make sure db.properties is in the CLASSPATH");
return;
}
String logFile = dbProps.getProperty("logfile",
"DBConnectionManager.log");
try {
log = new PrintWriter(new FileWriter(logFile, true), true);
}
catch (IOException e) {
System.err.println("Can not open the log file: " + logFile);
log = new PrintWriter(System.err);
}
loadDrivers(dbProps);
createPools(dbProps);
}
drivers=sun.jdbc.odbc.JdbcOdbcDriver jdbc.idbDriver
logfile=D:\\user\\src\\java\\DBConnectionManager\\log.txt
idb.url=jdbc:idb:c:\\local\\javawebserver1.1\\db\\db.prp
idb.maxconn=2
access.url=jdbc:odbc:demo
access.user=demo
access.password=demopw
private void loadDrivers(Properties props) {
String driverClasses = props.getProperty("drivers");
StringTokenizer st = new StringTokenizer(driverClasses);
while (st.hasMoreElements()) {
String driverClassName = st.nextToken().trim();
try {
Driver driver = (Driver)
Class.forName(driverClassName).newInstance();
DriverManager.registerDriver(driver);
drivers.addElement(driver);
log("Registered JDBC driver " + driverClassName);
}
catch (Exception e) {
log("Can not register JDBC driver: " + driverClassName + ", Exception: " + e);
}
}
}
private void createPools(Properties props) {
Enumeration propNames = props.propertyNames();
while (propNames.hasMoreElements()) {
String name = (String) propNames.nextElement();
if (name.endsWith(".url")) {
String poolName = name.substring(0, name.lastIndexOf("."));
String url = props.getProperty(poolName + ".url");
if (url == null) {
log("No URL specified for " + poolName);
continue;
}
String user = props.getProperty(poolName + ".user");
String password = props.getProperty(poolName + ".password");
String maxconn = props.getProperty(poolName + ".maxconn", "0");
int max;
try {
max = Integer.valueOf(maxconn).intValue();
}
catch (NumberFormatException e) {
log("Invalid maxconn value " + maxconn + " for " + poolName);
max = 0;
}
DBConnectionPool pool = new DBConnectionPool(poolName, url, user, password, max);
pools.put(poolName, pool);
log("Initialized pool " + poolName);
}
}
}
public Connection getConnection(String name) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
return pool.getConnection();
}
return null;
}
public Connection getConnection(String name, long time) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
return pool.getConnection(time);
}
return null;
}
public void freeConnection(String name, Connection con) {
DBConnectionPool pool = (DBConnectionPool) pools.get(name);
if (pool != null) {
pool.freeConnection(con);
}
}
public synchronized void release() {
// Wait until called by the last client
if (--clients != 0) {
return;
}
Enumeration allPools = pools.elements();
while (allPools.hasMoreElements()) {
DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();
pool.release();
}
Enumeration allDrivers = drivers.elements();
while (allDrivers.hasMoreElements()) {
Driver driver = (Driver) allDrivers.nextElement();
try {
DriverManager.deregisterDriver(driver);
log("Deregistered JDBC driver " + driver.getClass().getName());
}
catch (SQLException e) {
log(e, "Can not deregister JDBC driver: " + driver.getClass().getName());
}
}
}
当所有连接池关闭,所有jdbc驱动程序也被注销。
连结池的作用
现在我们结合DBConnetionManager和DBConnectionPool类来讲解servlet中连接池的使用:
一、首先简单介绍一下Servlet的生命周期:
Servlet API定义的servlet生命周期如下:
1、 Servlet 被创建然后初始化(init()方法)。
2、 为0个或多个客户调用提供服务(service()方法)。
3、 Servlet被销毁,内存被回收(destroy()方法)。
二、servlet中使用连接池的实例
使用连接池的servlet有三个阶段的典型表现是:
1. 在init()中,调用DBConnectionManager.getInstance()然后将返回的引用保存在实例变量中。
2. 在sevice()中,调用getConnection(),执行一系列数据库操作,然后调用freeConnection()归还连接。
3. 在destroy()中,调用release()来释放所有的资源,并关闭所有的连接。
下面的例子演示如何使用连接池。
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServlet extends HttpServlet {
private DBConnectionManager connMgr;
public void init(ServletConfig conf) throws ServletException {
super.init(conf);
connMgr = DBConnectionManager.getInstance();
}
public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
Connection con = connMgr.getConnection("idb");
if (con == null) {
out.println("Cant get connection");
return;
}
ResultSet rs = null;
ResultSetMetaData md = null;
Statement stmt = null;
try {
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM EMPLOYEE");
md = rs.getMetaData();
out.println("Employee data ");
while (rs.next()) {
out.println(" ");
for (int i = 1; i < md.getColumnCount(); i++) {
out.print(rs.getString(i) + ", ");
}
}
stmt.close();
rs.close();
}
catch (SQLException e) {
e.printStackTrace(out);
}
connMgr.freeConnection("idb", con);
}
public void destroy() {
connMgr.release();
super.destroy();
}
}