Connecting to Access database in Java Web project

Source: Internet
Author: User
Connection to Access database in Java Web project note: this blog is an upgrade to the "several methods for connecting JDBC to Access database" article a few days ago. I decided to write this blog only because of the problems I encountered when I was doing some small projects. I published my blog yesterday, but it was somewhat problematic after some verification. So I changed it today.

Connection to Access database in Java Web project note: this blog is an upgrade to "several methods for connecting to Access database through JDBC" in the last few days. I decided to write this blog only because of the problems I encountered when I was doing some small projects. I published my blog yesterday, but it was somewhat problematic after some verification. So I changed it today.

Java WebProjectMediumConnectionAccessDatabase

Note: This blog post is aboutConnectionAccessDatabaseSeveral methods. Because we are doing something smallProjectSo I decided to write this blog. I published my blog yesterday, but it was a bit problematic after some verification. So today I changed it and published it again.

The instructor decided to use access for the final examDatabaseFor addition, deletion, modification, and query, I think there is no problem now, but it was previously in the JSP pageConnectionAccessDatabaseIn either of the following ways:ConnectionBut now I want myProjectAccessDatabaseJava code, encapsulated in DAO, in DAOConnectionDatabase, Does not have any relationship with the Servlet API. Most people prefer to use ODBC data sources or absolute paths.ConnectionAccessDatabaseBut I personally think this is not very good. If this method is used,ProjectAfter the configuration is completed, it cannot be run on another person's server, becauseDatabaseThe information does not exist, and my current idea is thatProjectOn the server that supports the jdbc-odbc serverConnectionDatabase, And runProjectTo complete this operationDatabaseThe mdb FileProjectTherefore, in Java WebProjectTo put the mdb file under WebRoot or its subdirectory. But how can we get the actual path of the mdb in DAO?

In fact, this idea is basically the same as the idea of dynamically obtaining the path of the mdb File in JSP.

First, review the use of access in jspDatabaseRight!

For example, the following AccessDatabaseStudent, table basic, and six records are displayed in Jsp in several ways. :

For severalConnectionAccessDatabaseBasically is based on the JDBC-ODBC method, of course there are pure JDBC driver. I will not talk about it for the moment. In addition to obtainingConnectionOther codes are the same. Therefore, write and obtainConnectionAnd then use the complete code for display.

Method 1: direct bridge connection through JDBC-ODBCConnection:

1. For this method, you must first create an ODBC Data Source. My system is Windows 7, so select "Control Panel-management tools-Data Source (ODBC)" in sequence to open the data source Manager ,:

2. On the system DSN tab, click Add to open the create data source dialog box and select AccessDatabase"Microsoft Access Driver (*. mdb )":

3. Click the finish button, the following dialog box appears, enter the name of the data source "JDBC-ODBC" in the data source name, click the select button, selectDatabase"Student. mdb", click OK to complete data source configuration. :

4. After the data source is configured, you can get it by writing.ConnectionThe Code is 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 is through JDBC-ODBCConnectionAccessDatabaseKey code. This methodConnectionEasy to rememberConnectionThis is very useful. The subsequent code is normally written.

Method 2: PassDatabaseAbsolute pathConnection

The methods mentioned above are based on the JDBC-ODBC method. Therefore, the parameters in the Class. forName () of the driver are "sun. jdbc. odbc. JdbcOdbcDriver ". In this way, I put the student. mdb file under the root directory of the E disk.Database. ObtainConnectionThe Code is as follows:

Class. forName ("sun. jdbc. odbc. JdbcOdbcDriver ");

String url = "jdbc: odbc: driver = {Microsoft Access Driver (*. mdb)}; DBQ =" + "e: // student. mdb ";

Connection con = DriverManager. getConnection (url );

You do not need to configure the data source for this method. Although there are many codes, it is easy to understand. It is also very common.

Method 3: Get through the requestDatabaseAbsolute pathConnection

For this method, I personally think it is suitable for Java Web applications and can be used by others. I willDatabaseThe file is stored in the root path of the Web application. Dynamic acquisitionConnectionThe Code is 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)}; DBQ =" + path + "student. mdb ";

Connection con = DriverManager. getConnection (url );

The preceding three methods are available.Connection. The following is the displayed code. The Code is as follows:

<% @ Page language = "java" import = "java. util. *, java. SQL. * "contentType =" text/html; charset = UTF-8 "pageEncoding =" UTF-8 "%>            Access                
 <% 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.exe cuteQuery (SQL); while (rs. next () {%>
   <%} Rs. close (); st. close (); con. close (); %>
  
Student ID Name Age Address Chinese Mathematics English
<% = Rs. getString (1) %> <% = Rs. getString (2) %> <% = Rs. getInt (3) %> <% = Rs. getString (4) %> <% = Rs. getInt (5) %> <% = Rs. getInt (6) %> <% = Rs. getInt (7) %>

The result of running JSP is as follows:

WhenConnectionThe JSP code is as follows:

<% @ Page language = "java" import = "java. util. *, java. SQL. * "contentType =" text/html; charset = UTF-8 "pageEncoding =" UTF-8 "%>            Method 2 of JDBC <strong> connection </strong> Access <strong> database </strong>                
 <% Class. forName ("sun. jdbc. odbc. jdbcOdbcDriver "); String url =" jdbc: odbc: driver = {Microsoft Access Driver (*. mdb)}; DBQ = "+" e: // student. mdb "; Connection con = DriverManager. getConnection (url); Statement st = con. createStatement (); String SQL = "select * from basic"; ResultSet rs = st.exe cuteQuery (SQL); while (rs. next () {%>
   <%} Rs. close (); st. close (); con. close (); %>
  
Student ID Name Age Address Chinese Mathematics English
<% = Rs. getString (1) %> <% = Rs. getString (2) %> <% = Rs. getInt (3) %> <% = Rs. getString (4) %> <% = Rs. getInt (5) %> <% = Rs. getInt (6) %> <% = Rs. getInt (7) %>

The result of running JSP is as follows:

WhenConnectionThe JSP code is as follows:

<% @ Page language = "java" import = "java. util. *, java. SQL. * "contentType =" text/html; charset = UTF-8 "pageEncoding =" UTF-8 "%>            JDBC <strong> connection </strong> Access <strong> database </strong> method 3                
 <% 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)}; DBQ = "+ path +" student. mdb "; Connection con = DriverManager. getConnection (url); Statement st = con. createStatement (); String SQL = "select * from basic"; ResultSet rs = st.exe cuteQuery (SQL); while (rs. next () {%>
   <%} Rs. close (); st. close (); con. close (); %>
  
Student ID Name Age Address Chinese Mathematics English
<% = Rs. getString (1) %> <% = Rs. getString (2) %> <% = Rs. getInt (3) %> <% = Rs. getString (4) %> <% = Rs. getInt (5) %> <% = Rs. getInt (6) %> <% = Rs. getInt (7) %>

The result of running JSP is as follows:

For this method, myProjectThe directory structure is as follows:

The third method is used now. You can accessDatabase.

First, put the mdb file under WebRoot. When you click the hyperlink, send the information to the Servlet and write the following statement in the Servlet:

String path = request. getServletContext (). getRealPath ("/");
Dao dao = new Dao ();
Dao. init (path );
Initialize Connection in the init () method of daoConnection:

Class. forName ("sun. jdbc. odbc. JdbcOdbcDriver ");
String url = "jdbc: odbc: driver = {Microsoft Access Driver (*. mdb)}; DBQ =" + path + "student. mdb ";
Connection con = DriverManager. getConnection (url );

In this way, you can find it in dao Based on the passed path.DatabaseThe path of the file. And successfulConnectionToDatabaseImplementation of the hierarchical concept.

But there is a problem. If you put it under WebRoot, others will knowDatabaseIs it accessible?

For this reason, I thought for a long time, since it is accessed in the Java classDatabaseSo can we put the mdb file under src? The answer is yes. In this way, the file is copied to the Web in MyEclipse or Eclipse.ProjectUnder the WEB-INF classes root path, can not access, so my URL code becomes like this:

String url = "jdbc: odbc: driver = {Microsoft Access Driver (*. mdb)}; DBQ = student. mdb ";

But the result failed. The file was not found, but the file was put in the"Project", It is easy to make, but once it is given to others, it will not work, so it has to be put under src, only in this way will be put under WebRoot or WebContent, will be put under classes, to be accessed by the java class before being accessible to othersProjectTo run. But how can I findDatabaseFile. Always find a method until the following method is found:

Method 1: The getResource () method of the Class or


Method 2: getPath () method of the URL class

Use the getResource () method of the Class to find the directory of the current Class. Here, the dao Class is in com. student. under the dao package, the path of the class is returned by this method. If the parameter is "/", the root directory of the classes is returned, so thatDatabasePath of the mdb file. Then, use the getPath () method of the URL class to obtain the actual path of the file path of the string type on the server.

The Code is as follows:

String path = this. getClass (). getResource ("/"). getPath (). replaceAll ("% 20", ""); // The replaceAll method is used to solve the problem that the path contains space characters.

Path = path. substring (1, path. length (); // truncate the path and add a Class to the front of the obtained path. forName ("sun. jdbc. odbc. jdbcOdbcDriver ");

String url = "jdbc: odbc: driver = {Microsoft Access Driver (*. mdb)}; DBQ =" + path + "student. mdb ";

Con = DriverManager. getConnection (url );

Encapsulate the above Code in DAO to accessDatabase. In Java WebProjectUsing AccessDatabaseImplement the MVC design pattern and add DAO and VO. You can use Servlet APIs to pass the path of the mdb file to dao. Using dao to encapsulate Access is also a way. Sometimes you can put the mdb file under WebRoot for convenience, use JSP or ServletDatabaseFile Path to dao. AccessDatabaseThis is better.DatabaseAndProjectMove together. These two methods can be run on any machine.

At present, all I know is to do this. I also think this is a good practice. Java languageConnectionDatabase, SetDatabaseIt is good to put files in the same directory as the class path. If there are other methods, I hope you can come up with them.

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.