新聞中心
用Jdbc-odbc橋來連接,不過這可是犧牲了速度來的。用Jdbc-odbc橋的話,和連接access是一樣的,先要設置一個數(shù)據(jù)源DNS,然后就用:
Class.forName("sun.Jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("Jdbc:odbc:strurl",”
username”,”password”);

創(chuàng)新互聯(lián)專注于涇川企業(yè)網(wǎng)站建設,自適應網(wǎng)站建設,商城網(wǎng)站建設。涇川網(wǎng)站建設公司,為涇川等地區(qū)提供建站服務。全流程按需策劃,專業(yè)設計,全程項目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務
進行數(shù)據(jù)庫的鏈接是比較耗時的,如果頻繁刷新頁面,那就會不停的訪問數(shù)據(jù)庫,大大耗去了數(shù)據(jù)庫的資源。JSP提供了這樣一對函數(shù),JSPInit(),JSPDestory();如果要在JSP網(wǎng)頁開始執(zhí)行時,進行某些數(shù)據(jù)的初始化,則可以利用JSPInit函數(shù)來完成。此函數(shù)將在JSP網(wǎng)頁被執(zhí)行時調用,且當JSP網(wǎng)頁重新整理時,并不會被再度執(zhí)行。當關閉服務器時,JSPDestory函數(shù)將被調用,可利用該函數(shù)來完成數(shù)據(jù)的善后處理。
可以利用JSPInit和JSPDestory函數(shù)來完成數(shù)據(jù)庫的鏈接和關閉。在JSPInit中進行數(shù)據(jù)庫的鏈接,可以避免每次刷新頁面時都要鏈接數(shù)據(jù)庫,提高了工作效率。
以下是代碼實例:
- <%!
- Connection conn=null;
- Statement st=null;
- ResultSet rs=null;
- Public void jspInit()
- {
- Try
- {
- //加載驅動程序類
- Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
- //連接數(shù)據(jù)庫
- Connection conn=DriverManager.getConnection("jdbc:odbc:strurl",”
- username”,”password”);
- //建立Statement對象
- St=conn.CreateStatement();
- }
- Catch(Exception ex)
- {
- System.out.println(ex.toString());
- }
- }
- Public void jspDestroy()
- {
- try
- {
- rs.close();
- st.,close();
- conn.close();
- }
- catch(Exception ex)
- {
- System.out.println(ex.toString());
- }
- }
- %>
當JSP網(wǎng)頁從數(shù)據(jù)庫中取得數(shù)據(jù)時,最耗費服務器時間的是建立數(shù)據(jù)庫鏈接。用JSPInit
和JSPDestory函數(shù)并不是非常好的辦法,畢竟每瀏覽一次新網(wǎng)頁,就要建立數(shù)據(jù)庫鏈
接。這個時候可以為一個聯(lián)機者建立一個數(shù)據(jù)庫鏈接。這里我們利用Bean對象來建立數(shù)
據(jù)庫鏈接。
以下是代碼實例:
- //定義bean所屬的套件
- package com.test;
- import java.io.*;
- import java.sql.*;
- import javax.servlet.http.*;
- public class conn implements HttpSessionBindingListener
- {
- private Connection con=null;
- public conn() //在構造函數(shù)中完成數(shù)據(jù)庫鏈接
- {
- BulidConnection();
- }
- private void BulidConnection()
- {
- try
- {
- //載入驅動程序
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
- }
- catch(java.lang.ClassNotFoundException e1)
- {
- System.out.println("數(shù)據(jù)庫驅動加載失敗
");- }
- try
- {
- //建立數(shù)據(jù)庫鏈接
- con=DriverManager.getConnection("jdbc:odbc:test","test","test");
- }
- catch(SQLException e2)
- {
- System.out.println("數(shù)據(jù)庫連接失敗");
- }
- }
- //取得Connection對象
- public Connection getConnection()
- {
- if(con==null)
- BulidConnection();
- return this.con;
- }
- public void close()
- {
- try
- {
- con.close();
- con=null;
- }
- catch(SQLException sex)
- {
- System.out.println(sex.toString());
- }
- }
- //當物體加入session時,將自動執(zhí)行此函數(shù)
- public void valueBound(HttpSessionBindingEvent event){}
- //當session對象刪除時,將自動執(zhí)行此函數(shù)
- public void valueUnbound(HttpSessionBindingEvent event)
- {
- if(con!=null)
- close();//調用close方法
- }
- }
分享名稱:JSP的Init和Destory函數(shù)提高工作效率
文章轉載:http://m.5511xx.com/article/cdhescp.html


咨詢
建站咨詢
