1. create the folder "AccessDb" under the site (my site is: E: \ javatest) and create the Database "test. mdb and table stu. The stu field is id and stuname test. mdb path: E: \ javatest \ AccessDb
For example:
2. Create the test connection database file "AccessTest. jsp" at the site (E: \ javatest"
The Code is as follows:
<% @ 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 connection test </title>
</Head>
<Body>
<%
Try {
Class. forName ("sun. jdbc. odbc. JdbcOdbcDriver ");
}
Catch (ClassNotFoundException e ){
Out. print (e );
}
Try {
// Absolute path
// String url = "jdbc: odbc: driver = {Microsoft Access Driver (*. mdb)}; DBQ = E:/javatest/AccessDb/test. mdb ";
// E:/javatest/AccessDb/test. mdb indicates the absolute path of the database.
// Relative path
String strDirPath = getServletContext (). getRealPath ("/"); // obtain the absolute path of the site: E: \ javatest \
// Out. print (strDirPath + "<br> ");
StrDirPath = strDirPath. replace ('\', '/'); // replace "\" with "/" 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 ";
// Establish an ODBC data source connection
Connection conn = DriverManager. getConnection (url );
Statement stmt = conn. createStatement ();
ResultSet rs = stmt.exe cuteQuery ("Select * FROM stu"); // retrieves records FROM the stu table
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>
The running result is as follows: