在jsp中連接到oracle一般有2種方式:
1、oracle jdbc的oci8方式
2、oracle jdbc的thin方式
我比較喜歡第2種,因?yàn)閣eb發(fā)布服務(wù)器與數(shù)據(jù)庫(kù)服務(wù)器一般都不會(huì)放在同一臺(tái)電腦中,而在使用thin方式連接時(shí),web服務(wù)器端無(wú)須安裝oracle的客戶(hù)端。
在動(dòng)手先代碼之前,我們先把環(huán)境配置妥善。先從安裝了oracle的數(shù)據(jù)庫(kù)服務(wù)器中,找到oracle安裝目錄,然后將該目錄下的jdbc/lib/classes12.jar文件拷貝到web發(fā)布服務(wù)器的某個(gè)目錄。假設(shè)就直接放在c:/根目錄下吧,然后把該路徑添加到‘系統(tǒng)--高級(jí)--環(huán)境變量’中變量名為‘classpath’的值中,如:d:/program files/sqllib/java/db2java.zip;d:/program files/sqllib/java/runtime.zip;c:classes12.jar; 也就是讓java能夠找到這個(gè)包。
配置好環(huán)境后,我們就開(kāi)始開(kāi)始動(dòng)手寫(xiě)代碼了。關(guān)于數(shù)據(jù)庫(kù)連接的代碼,應(yīng)該寫(xiě)個(gè)專(zhuān)門(mén)的連接類(lèi)來(lái)調(diào)用,沒(méi)必要想網(wǎng)絡(luò)上有些文章那樣,直接寫(xiě)到j(luò)sp的代碼中。
關(guān)于連接的代碼很簡(jiǎn)單
private connection newconnection(string user,string password) {
connection con = null;
try {
class.forname("oracle.jdbc.driver.oracledriver").newinstance();
con = drivermanager.getconnection (“jdbc:oracle:thin:@192.168.96.1:1521:oracle9i”,user,password);
}
catch (sqlexception e) {
return null;
}
return con;
}
如果帳號(hào)密碼沒(méi)有錯(cuò),那這個(gè)函數(shù)就應(yīng)該能返回個(gè)可用的連接。但如此簡(jiǎn)單的連接在一個(gè)項(xiàng)目中使用,是遠(yuǎn)遠(yuǎn)達(dá)不到效果的。我們可以在這個(gè)數(shù)據(jù)庫(kù)連接類(lèi)中加入更多的功能,如連接池等等。下面我就把該數(shù)據(jù)庫(kù)連接類(lèi)的代碼詳細(xì)的列出來(lái),大家可以參考參考。
/*
* @title 公司網(wǎng)站
* @author: zf
* @version 1.0
* @memo:定義數(shù)據(jù)庫(kù)連接及其數(shù)據(jù)庫(kù)連接池等
*/
package com.kingson.db;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.date;
public class dbconnectionmanager {
static private dbconnectionmanager instance; // 唯一實(shí)例
static private int clients;
private vector drivers = new vector();
private printwriter log;
private hashtable pools = new hashtable();
/**
* 返回唯一實(shí)例.如果是第一次調(diào)用此方法,則創(chuàng)建實(shí)例
*
* @return dbconnectionmanager 唯一實(shí)例
*/
static synchronized public dbconnectionmanager getinstance() {
if (instance == null) {
instance = new dbconnectionmanager();
}
clients++;
return instance;
}
/**
* 建構(gòu)函數(shù)私有以防止其它對(duì)象創(chuàng)建本類(lèi)實(shí)例
*/
private dbconnectionmanager() {
init();
}
/**
* 將連接對(duì)象返回給由名字指定的連接池
*
* @param name 在屬性文件中定義的連接池名字
* @param con 連接對(duì)象
*/
public void freeconnection(string name, connection con) {
dbconnectionpool pool = (dbconnectionpool) pools.get(name);
if (pool != null) {
pool.freeconnection(con);
}
}
/**
* 獲得一個(gè)可用的(空閑的)連接.如果沒(méi)有可用連接,且已有連接數(shù)小于最大連接數(shù)
* 限制,則創(chuàng)建并返回新連接
*
* @param name 在屬性文件中定義的連接池名字
* @return connection 可用連接或null
*/
public connection getconnection(string name) {
dbconnectionpool pool = (dbconnectionpool) pools.get(name);
if (pool != null) {
return pool.getconnection();
}
return null;
}
/**
* 獲得一個(gè)可用連接.若沒(méi)有可用連接,且已有連接數(shù)小于最大連接數(shù)限制,
* 則創(chuàng)建并返回新連接.否則,在指定的時(shí)間內(nèi)等待其它線程釋放連接.
*
* @param name 連接池名字
* @param time 以毫秒計(jì)的等待時(shí)間
* @return connection 可用連接或null
*/
public connection getconnection(string name, long time) {
dbconnectionpool pool = (dbconnectionpool) pools.get(name);
if (pool != null) {
return pool.getconnection(time);
}
return null;
}
/**
* 關(guān)閉所有連接,撤銷(xiāo)驅(qū)動(dòng)程序的注冊(cè)
*/
public synchronized void release() {
// 等待直到最后一個(gè)客戶(hù)程序調(diào)用
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("撤銷(xiāo)jdbc驅(qū)動(dòng)程序 " + driver.getclass().getname()+"的注冊(cè)");
}
catch (sqlexception e) {
log(e, "無(wú)法撤銷(xiāo)下列jdbc驅(qū)動(dòng)程序的注冊(cè): " + driver.getclass().getname());
}
}
}
/**
* 根據(jù)指定屬性創(chuàng)建連接池實(shí)例.
*
* @param props 連接池屬性
*/
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("沒(méi)有為連接池" + poolname + "指定url");
continue;
}
string user = props.getproperty(poolname + ".user");
string password = props.getproperty(poolname + ".password");
string dbip = props.getproperty(poolname + ".db_ip", "192.168.96.1");
string dbport = props.getproperty(poolname + ".db_port", "1521");
string dbuid = props.getproperty(poolname + ".db_uid", "oracle9i");
string maxconn = props.getproperty(poolname + ".maxconn", "0");
//連接信息
string dbinfo = user + "/" + password + "@" + dbip + ":" + dbport + ":" + dbuid;
int max;
try {
max = integer.valueof(maxconn).intvalue();
}
catch (numberformatexception e) {
log("錯(cuò)誤的最大連接數(shù)限制: " + maxconn + " .連接池: " + poolname);
max = 0;
}
dbconnectionpool pool = new dbconnectionpool(poolname, url,dbinfo, max);
pools.put(poolname, pool);
log("成功創(chuàng)建連接池" + poolname);
}
}
}
/**
* 讀取屬性完成初始化
*/
private void init() {
inputstream is = getclass().getresourceasstream("db.properties");
properties dbprops = new properties();
try {
dbprops.load(is);
}
catch (exception e) {
system.err.println("不能讀取屬性文件. " +
"請(qǐng)確保db.properties在classpath指定的路徑中");
return;
}
string logfile = dbprops.getproperty("logfile", "newslog.txt");
try {
log = new printwriter(new filewriter(logfile, true), true);
}
catch (ioexception e) {
system.err.println("無(wú)法打開(kāi)日志文件: " + logfile);
log = new printwriter(system.err);
}
loaddrivers(dbprops);
createpools(dbprops);
}
/**
* 裝載和注冊(cè)所有jdbc驅(qū)動(dòng)程序
*
* @param props 屬性
*/
private void loaddrivers(properties props) {
string driverclasses = props.getproperty("driver");
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("成功注冊(cè)jdbc驅(qū)動(dòng)程序" + driverclassname);
}
catch (exception e) {
log("無(wú)法注冊(cè)jdbc驅(qū)動(dòng)程序: " +
driverclassname + ", 錯(cuò)誤: " + e);
}
}
}
/**
* 將文本信息寫(xiě)入日志文件
*/
private void log(string msg) {
log.println(new date() + ": " + msg);
}
/**
* 將文本信息與異常寫(xiě)入日志文件
*/
private void log(throwable e, string msg) {
log.println(new date() + ": " + msg);
e.printstacktrace(log);
}
/***************連接池類(lèi)*************************************************/
/**
* 此內(nèi)部類(lèi)定義了一個(gè)連接池.它能夠根據(jù)要求創(chuàng)建新連接,直到預(yù)定的最
* 大連接數(shù)為止.在返回連接給客戶(hù)程序之前,它能夠驗(yàn)證連接的有效性.
*/
class dbconnectionpool {
private int checkedout;
private vector freeconnections = new vector();
private int maxconn;
private string name;
private string url;
private string dbinfo;
/**
* 創(chuàng)建新的連接池
*
* @param name 連接池名字
* @param url 數(shù)據(jù)庫(kù)的jdbc url
* @param dbinfo 數(shù)據(jù)庫(kù)連接信息
* @param maxconn 此連接池允許建立的最大連接數(shù)
*/
public dbconnectionpool(string name, string url, string dbinfo, int maxconn) {
this.name = name;
this.url = url;
this.dbinfo = dbinfo;
this.maxconn = maxconn;
}
/**
* 將不再使用的連接返回給連接池
*
* @param con 客戶(hù)程序釋放的連接
*/
public synchronized void freeconnection(connection con) {
// 將指定連接加入到向量末尾
freeconnections.addelement(con);
checkedout--;
notifyall();
}
/**
* 從連接池獲得一個(gè)可用連接.如沒(méi)有空閑的連接且當(dāng)前連接數(shù)小于最大連接
* 數(shù)限制,則創(chuàng)建新連接.如原來(lái)登記為可用的連接不再有效,則從向量刪除之,
* 然后遞歸調(diào)用自己以嘗試新的可用連接.
*/
public synchronized connection getconnection() {
connection con = null;
if (freeconnections.size() > 0) {
// 獲取向量中第一個(gè)可用連接
con = (connection) freeconnections.firstelement();
freeconnections.removeelementat(0);
try {
if (con.isclosed()) {
log("從連接池" + name+"刪除一個(gè)無(wú)效連接");
// 遞歸調(diào)用自己,嘗試再次獲取可用連接
con = getconnection();
}
}
catch (sqlexception e) {
log("從連接池" + name+"刪除一個(gè)無(wú)效連接");
// 遞歸調(diào)用自己,嘗試再次獲取可用連接
con = getconnection();
}
}
else if (maxconn == 0 || checkedout < maxconn) {
con = newconnection();
}
if (con != null) {
checkedout++;
}
return con;
}
/**
* 從連接池獲取可用連接.可以指定客戶(hù)程序能夠等待的最長(zhǎng)時(shí)間
* 參見(jiàn)前一個(gè)getconnection()方法.
*
* @param timeout 以毫秒計(jì)的等待時(shí)間限制
*/
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) {
// wait()返回的原因是超時(shí)
return null;
}
}
return con;
}
/**
* 關(guān)閉所有連接
*/
public synchronized void release() {
enumeration allconnections = freeconnections.elements();
while (allconnections.hasmoreelements()) {
connection con = (connection) allconnections.nextelement();
try {
con.close();
log("關(guān)閉連接池" + name+"中的一個(gè)連接");
}
catch (sqlexception e) {
log(e, "無(wú)法關(guān)閉連接池" + name+"中的連接");
}
}
freeconnections.removeallelements();
}
/**
* 創(chuàng)建新的連接
*/
private connection newconnection() {
connection con = null;
try {
con = drivermanager.getconnection(url+dbinfo);
log("連接池" + name+"創(chuàng)建一個(gè)新的連接");
}
catch (sqlexception e) {
log(e, "無(wú)法創(chuàng)建下列url的連接: " + url);
return null;
}
return con;
}
}
}
新聞熱點(diǎn)
疑難解答
圖片精選