簡單介紹JSP數(shù)據(jù)庫鏈接
用Jdbc-odbc橋來連接,不過這可是犧牲了速度來的。用Jdbc-odbc橋的話,和連接access是一樣的,先要設(shè)置一個數(shù)據(jù)源DNS,然后就用:
◆Class.forName("sun.Jdbc.odbc.JdbcOdbcDriver");
◆Connection conn=DriverManager.getConnection("Jdbc:odbc:strurl",”
◆username”,”password”);
進(jìn)行數(shù)據(jù)庫的鏈接是比較耗時的,如果頻繁刷新頁面,那就會不停的訪問數(shù)據(jù)庫,大大耗去了數(shù)據(jù)庫的資源。JSP提供了這樣一對函數(shù),JSP Init(),JSP Destory();如果要在JSP網(wǎng)頁開始執(zhí)行時,進(jìn)行某些數(shù)據(jù)的初始化,則可以利用JSP Init函數(shù)來完成。此函數(shù)將在JSP網(wǎng)頁被執(zhí)行時調(diào)用,且當(dāng)JSP網(wǎng)頁重新整理時,并不會被再度執(zhí)行。當(dāng)關(guān)閉服務(wù)器時,JSP Destory函數(shù)將被調(diào)用,可利用該函數(shù)來完成數(shù)據(jù)的善后處理。
可以利用JSP Init和JSP Destory函數(shù)來完成數(shù)據(jù)庫的鏈接和關(guān)閉。在JSP Init中進(jìn)行數(shù)據(jù)庫的鏈接,可以避免每次刷新頁面時都要鏈接數(shù)據(jù)庫,提高了工作效率。
以下是代碼實例:
- <%!
- Connection conn=null;
- Statement st=null;
- ResultSet rs=null;
- Public void jspInit()
- {
- Try
- {
- //加載驅(qū)動程序類
- 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());
- }
- }
- %>
當(dāng)JSP網(wǎng)頁從數(shù)據(jù)庫中取得數(shù)據(jù)時,最耗費服務(wù)器時間的是建立數(shù)據(jù)庫鏈接。用JSP Init
和JSP Destory函數(shù)并不是非常好的辦法,畢竟每瀏覽一次新網(wǎng)頁,就要建立數(shù)據(jù)庫鏈
接。這個時候可以為一個聯(lián)機(jī)者建立一個數(shù)據(jù)庫鏈接。這里我們利用Bean對象來建立數(shù)
據(jù)庫鏈接。
以下是代碼實例:
- conn.java
- //定義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() //在構(gòu)造函數(shù)中完成數(shù)據(jù)庫鏈接
- {
- BulidConnection();
- }
- private void BulidConnection()
- {
- try
- {
- //載入驅(qū)動程序
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
- }
- catch(java.lang.ClassNotFoundException e1)
- {
- System.out.println("數(shù)據(jù)庫驅(qū)動加載失敗<br>");
- }
- 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());
- }
- }
- //當(dāng)物體加入session時,將自動執(zhí)行此函數(shù)
- public void valueBound(HttpSessionBindingEvent event){}
- //當(dāng)session對象刪除時,將自動執(zhí)行此函數(shù)
- public void valueUnbound(HttpSessionBindingEvent event)
- {
- if(con!=null)
- close();//調(diào)用close方法
- }
- }
【編輯推薦】