Configuration method for connecting an Access database in a Java Web project _jsp programming

Source: Internet
Author: User
Tags odbc access database java web

The teacher decided to use Access database to implement the final exam, I think now I have no problem, but the previous is in the JSP page to connect Access database, regardless of the way the following are connected to the practice, But now I want the Java code in my project to access the Access database, encapsulated in DAO, connected to the database in DAO, without any relationship to the Servlet API. For most people who prefer to use an ODBC data source or use an absolute path to connect to an Access database, but I personally think that this is not very good, if in this way, the project is done, put on the other people's server can not run, because the database information does not exist, And my idea now is that no matter where the project is on the server that supports the JDBC-ODBC machine, you can connect to the database and run the project, so to do so, only if the MDB file for the Access database moves with the project, so in the Java Web project, Put the MDB file under Webroot or under its subdirectories. But how do you get the true path of the MDB in DAO?

In fact, the idea of getting the path to the MDB file dynamically in the JSP is basically the same.

Let's review the JSP to use the Access database!

For example, the following Access database student, table Basic, and 6 records, now display their data in a JSP in several ways. As shown in the figure:

For several ways to connect to an Access database, it is basically based on the JDBC-ODBC approach and, of course, a pure JDBC-driven approach. I'm not going to say this here for a while. For each of these ways, other code is the same except to get a connection. So here are some ways to get a connection, and then use the full code to display it.

Way one: Through the Jdbc-odbc Way Bridge connects directly:

1, for this way, first to establish an ODBC data source, my system is Win7 system, so select the Control Panel----management tools----data source (ODBC), open the data Source Manager, as shown in the figure:

2. On the System DSN tab, click the Add button, open the Create Data Source dialog box, select the driver for the Access database, Microsoft access Driver (*.mdb), as shown in the figure:

3, click the Completion button, the following dialog box appears, enter the name of the data source in the data source name "Jdbc-odbc", click the Select button, select the database to operate "Student.mdb", click OK button to complete the configuration of the data source. As shown in the figure:

4, the data source configuration is good, you can write to get the connection code, as follows:

Copy Code code as follows:

Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
String url = "Jdbc:odbc:jdbc-odbc";
Connection con = drivermanager.getconnection (URL);


The above three lines of code are key to connecting Access databases via JDBC-ODBC. This way it is useful to connect to the URL code that can be easily memorized by the connection. The following code is normally written.

mode two: Connect through the absolute path of the database

It is said that several ways are based on the JDBC-ODBC approach. So the parameters in the load-driven class.forname () are "Sun.jdbc.odbc.JdbcOdbcDriver". For this way I put the Student.mdb file in the root of e disk, when used, write directly to the absolute path of the database line. The code to get the connection looks like this:

Copy Code code as follows:

Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
String url = "Jdbc:odbc:driver={microsoft Access driver (*.mdb)};D bq=" + "E://student.mdb";
Connection con = drivermanager.getconnection (URL);


There is no need to configure the data source for this way, although the code is more, but it is well understood. is also very common.

mode three: To obtain the absolute path of the database by request connection

In this way, I personally think it is suitable for use in Java Web Applications, will do a good job for others, others can use. I placed the database file under the root path of the Web application. The code that dynamically gets the connection is as follows:

Copy Code code as follows:

String Path = Application.getrealpath ("/index.jsp");
Path = path.substring (0,path.lastindexof ("\")) + "\";
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
String url = "Jdbc:odbc:driver={microsoft Access driver (*.mdb)};D bq=" +path+ "Student.mdb";
Connection con = drivermanager.getconnection (URL);


The above is three ways to get the connection. The next step is to display the code. The code looks like this:

Copy Code code as follows:

<%@ page language= "java" import= "java.util.*,java.sql.*" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<title>Access</title>
<body>
<table border= "1" width= "40%" >
<tr bgcolor= "Gray" >
<th> School Number </th>
<th> name </th>
<th> Age </th>
<th> Address </th>
<th> Languages </th>
<th> Math </th>
<th> English </th>
</tr>
<%
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
String url = "Jdbc:odbc:jdbc-odbc";
Connection con = drivermanager.getconnection (URL);
Statement st = Con.createstatement ();
String sql = "SELECT * from basic";
ResultSet rs = st.executequery (SQL);
while (Rs.next ())
{
%>
<tr>
<td><%=rs.getstring (1)%></td>
<td><%=rs.getstring (2)%></td>
<td><%=rs.getint (3)%></td>
<td><%=rs.getstring (4)%></td>
<td><%=rs.getint (5)%></td>
<td><%=rs.getint (6)%></td>
<td><%=rs.getint (7)%></td>
</tr>
<%
}
Rs.close ();
St.close ();
Con.close ();
%>
</table>
</body>


The results of running the JSP are as follows:

When you change the connection to the second way, the JSP code looks like this:

<%@ page language= "java" import= "java.util.*,java.sql.*" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
 

The results of running the JSP are as follows:

When you change the connection to a third way, the JSP code looks something like this:

<%@ page language= "java" import= "java.util.*,java.sql.*" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

The results of running the JSP are as follows:

For this way my project's directory structure looks like this:

The third way is just the way it is now, and you can access the database in the Java class.
First put the MDB file under Webroot, and when you click on the hyperlink, pass the message to the servlet and write the following statement in the servlet:
String path = Request.getservletcontext (). Getrealpath ("/");
DAO dao = new Dao ();
Dao.init (path);
Initialize the connection connection in the DAO's init () method:
Class.forName ("Sun.jdbc.odbc.JdbcOdbcDriver");
String url = "Jdbc:odbc:driver={microsoft Access driver (*.mdb)};D bq=" +path+ "Student.mdb";
Connection con = drivermanager.getconnection (URL);
This allows you to find the path to the database file in the DAO based on your path. and successfully connected to the database, the realization of a layered concept.
But this has a problem, if put in Webroot, others know the location of the database, can not access it?
For this I think for a long time, since it is in the Java class access to the database, then you can put the MDB file under SRC, the answer is yes. So in MyEclipse or eclipse, the file is copied to the classes root path under the Web-inf of the Web project, not accessible, so my URL code becomes this:
String url = "Jdbc:odbc:driver={microsoft Access driver (*.mdb)};D Bq=student.mdb";
But the results failed, did not find the file, but later put the file under the "project", it works, but so once given to others, and then die, so still have to put under SRC, only in this way will be placed under the Webroot or webcontent, will be placed under the classes, can be accessed by Java classes before they can be run by a project. But how to find the database files in the classes directory. have been looking for a method until you find the following method:
Method one: Class class GetResource () method or ClassLoader class

Method Two: The GetPath () method of the URL class
Find the directory where the current class is located through the class GetResource () method, where the DAO class is under the Com.student.dao package, then the method returns the path of the class, and if the parameter is "/", it returns the classes root directory. This allows you to get the path to the database MDB file under classes. Then the GetPath () method of the URL class gets the true path of the file path of the string type on the server.
The code looks like this:
String path = This.getclass (). GetResource ("/"). GetPath (). ReplaceAll ("%20", "");//replaceall method to resolve problems with whitespace characters in the path
Path = Path.substring (1,path.length ());//The path is intercepted, and an additional bar class.forname ("Sun.jdbc.odbc.JdbcOdbcDriver") will be added to the paths obtained.
String url = "Jdbc:odbc:driver={microsoft Access driver (*.mdb)};D bq=" +path+ "Student.mdb";
con = drivermanager.getconnection (URL);
You can access the database by encapsulating the code above in the DAO. You can use an Access database to implement the MVC design pattern in a Java Web project, and add DAO and VO. It is a way to use the Servlet API to pass the path of an MDB file to DAO, and it is also a way to use DAO encapsulation of access, sometimes for the convenience of putting the MDB file under Webroot and passing the path of the database file through a JSP or a servlet to DAO. I think the Access database is a better place to move the database and the project together. Customs clearance of these two ways can be run on any machine.
At present, what I know is doing so, and I think it is a better approach. Connecting a database In the Java language is a good way to put the database files in the same directory as the classpath. If there are other ways, I hope you will come forward.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.