Use Access to create a database. Assume that you can save it as D: mydata. mdb to connect to the Access database in two ways: directly using the Access driver, and using 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 JDBC-OD
Use Access to create a database. Assume that you can save it as D:/mydata. mdb to connect to the Access database in two ways: directly using the Access driver, and using 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 JDBC-OD
Use Access to createDatabaseAnd save it as D:/mydata. mdb.
Link AccessDatabaseThere are two methods, one is directUseThe Access driver, and The DSN link. We first define several variables in the method. filePath refersDatabaseFile address. The url is a link.DatabaseDbDriver is the JDBC-ODBC driver, and dsn is the dsn name defined by the system.
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 string), and DriverManager. SQLException thrown by getConnection (String url.
When using DSN to link AccessDatabaseYou 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. Below we construct the linkDatabaseMethod:
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;
}