当前位置:首页 > JSP教程 > JSP常见问题

Jsp连接Access数据库(不通过建立ODBC数据源的方法)

1. 在站点(我的站点为:e:javatest)下建立文件夹“accessdb”并在文件夹下建立数据库“test.mdb”以及表“stu”,stu字段为 id,stuname      test.mdb所在路径为:e:javatestaccessdb 下面
如下图:


2.在站点(e:javatest)下建立测试连接数据库文件“accesstest.jsp”
代码如下:

<%@ page contenttype="text/html; charset=gb2312" language="java" import="java.sql.*" errorpage="" %>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<title>access连接测试</title>
</head>

<body>
<%
try{
  class.forname("sun.jdbc.odbc.jdbcodbcdriver");
}
catch(classnotfoundexception e){
  out.print(e);
}
try{
  //绝对路径
  //string url = "jdbc:odbc:driver={microsoft access driver (*.mdb)};dbq=e:/javatest/accessdb/test.mdb";
  //其中 e:/javatest/accessdb/test.mdb 为数据库所在绝对路径

  //相对路径
  string strdirpath=getservletcontext().getrealpath("/");              //获得所在站点的绝对路径:e:javatest
  //out.print(strdirpath+"<br>");

  strdirpath=strdirpath.replace('\','/');                             //将“”替换为“/”      e:/javatest/
  //out.print(strdirpath+"<br>");

  string url = "jdbc:odbc:driver={microsoft access driver (*.mdb)};dbq="+strdirpath+"accessdb/test.mdb";
  //out.print(url+"<br>");

  //string url = "jdbc:odbc:accesstest";
  //建立odbc数据源连接

  connection conn = drivermanager.getconnection(url);
  statement stmt = conn.createstatement();
  resultset rs = stmt.executequery("select * from stu");              //取得stu表中的记录
  out.println("table-list"+"<br>");
  while(rs.next()){
    out.print(rs.getint(1)+" ");
    out.print(rs.getstring(2)+"<br>");
  }
  rs.close();
  stmt.close();
  conn.close();
}
catch(exception ex){
  out.print(ex);
}
%>
</body>
</html>

运行结果如下:






【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!