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;
}