Use a JDBC-ODBC to link to an Access database

Source: Internet
Author: User
Tags access database

Create a database with access, and save it as D:/mydata. MDB.

There are two ways to connect to the Access Database: one is to directly use the access driver, and the other is to use the DSN link. We first define several variables in the method, filepath refers to the address of the database file, URL is the string linking the database, dbdriver is the JDBC-ODBC driver, DSN is the system defined DSN name.

The method to connect through the driver is as follows:

 

Public static connection getconnection () throws exception {

String filepath = "D: // mydata. mdb ";

String url = "JDBC: ODBC: Driver = {Microsoft Access Driver (*. mdb)}; DBQ =" + filepath;

String dbdriver = "Sun. JDBC. ODBC. jdbcodbcdriver ";

 

Class. forname (dbdriver );

Connection conn = drivermanager. getconnection (URL );

Return conn;

}

 

At this point, this method has been completed, and the method will throw two exceptions. One is class. classnotfoundexception thrown by forname (string), and drivermanager. sqlexception thrown by getconnection (string URL.

 

When using DSN to connect to the Access database, you must first set the ODBC data source for Windows. The specific settings are as follows:

Control Panel → (system performance and appearance) → Administrative Tools → ODBC Data Source → Add a user DSN or system DSN as needed ".

Here we add a system DSN named mydata. The following describes how to construct a database link:

 

Public static connection getconnection () throws exception {

String DSN = "mydata ";

String url = "JDBC: ODBC:" + DSN;

String dbdriver = "Sun. JDBC. ODBC. jdbcodbcdriver ";

 

Class. forname (dbdriver );

Connection conn = drivermanager. getconnection (URL );

Return conn;

}

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.