iLMS知識社群歷程檔登入
位置: 廖俊維 > 資料庫
JSP連結ACCESS資料庫
by 廖俊維 2012-11-24 09:44:05, 回應(0), 人氣(1323)
作業系統:Windows XP
Web Server:Apache Tomcat 7.0
DB: Access 2003
 
假設有一個「會員登入」的交易,
server要準備一個login.html供用戶端輸入帳號及密碼,
server端處理此交易的程式是login.jsp,
帳號密碼存在一個member.mdb的Access 2003資料庫中的account資料表中,
account資料表的結構,有3個欄位,一個是id,一個是password,一個是name,都是文字型別。
步驟一:準備login.html
<div align="center">
<form method="POST" action="login.jsp">
 <table border="1" width="29%" id="table2">
  <tr>
   <td width="48" nowrap>帳號</td>
   <td><input type="text" name="id" size="20"></td>
  </tr>
  <tr>
   <td width="48">密碼</td>
   <td><input type="password" name="pwd" size="20"></td>
  </tr>
 </table>
 <input type="submit" value="送出" name="B1"><input type="reset" value="重新設定" name="B2">
</form>
</div>
步驟二:接著設定資料庫member.mdb的ODBC
在控制台/系統管理工具/資料來源 (ODBC),其中「系統資料來源名稱」,按「新增」;
選取Microsoft access Driver (*.mdb)驅動程式,按完成。
接著為你的資料庫檔案,自訂一個名稱,在login.jsp會用到。
再按資料庫的「選取」,選取你的資料庫檔案所在的磁碟機、目錄、資料庫檔案,按「確定」,
回到「ODBC Microsoft Access設定」,再按一次「確定」。
 
 會看到「系統資料來源」中,多了一個剛才新增的「myDB」,記住這個名稱,按「確定」。
 
 步驟三:準備login.jsp

<%@ page import = "java.sql.*" contentType="text/html;charset=big5" %>
<% String id = request.getParameter("id"); %>
<% String pwd = request.getParameter("pwd"); %>

<html>
 <head>
   <title>會員登入</title>
   <meta http-equiv="Content-Type" content="text/html;charset=big5">
   <meta http-equiv="Content-Language" content="zh-tw">
 </head>
 <body>

 <%

  //載入驅動程式
  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  
  //建立與資料庫的連結
  Connection connSampleDB = DriverManager.getConnection("jdbc:odbc:myDB","","");
  
  //進入資料庫取得資料
 
  Statement Stmt = connSampleDB.createStatement();
  ResultSet Rs;
  id = id.replace('\'',' ');
  pwd = pwd.replace('\'',' ');

  id= id.toLowerCase();
  pwd=pwd.toLowerCase();

  Rs = Stmt.executeQuery("Select * From account where id = '" + id + "' and password='" + pwd + "'");
   
    if(Rs.next()){
       //找到
       String name = Rs.getString("name");
       out.println("會員" + name + "您好,登入成功!");
    }
    else
    {  //找不到
       out.println("登入失敗,帳號或密碼為身份證!");
    }
  //關閉連結
  connSampleDB.close();
  out.println("<hr>資料庫關閉!");
 %>
 </body>
</html>

執行畫面與結果如下:
架構圖如下:

PS: JAVA 8 據說不支援ODBC-JDBC了,
請參考 UCanAccess
的最後一則留言
回應