java web应用连接access数据库的方法
1、下载ucanaccess驱动jar包,下载地址是https://sourceforge.net/projects/ucanaccess/,将下载后解压得到的几个jar文件导入到web应用的WEB-INF/lib文件夹下。共有ucanaccess-5.0.1.jar、commons-lang3-3.8.1.jar、commons-logging-1.2.jar、hsqldb-2.5.0.jar、jackcess-3.0.1.jar等几个jar文件。
2、准备access数据库文件,放在本地电脑任意位置。建议放在项目的build\classes文件夹里,这样可以通过以下两条语句读出其位置path:
String path = this.getClass().getResource("/").getPath().replaceAll("%20"," ");//replaceAll方法是为了解决路径中含有空格字符的问题 path = path.substring(1,path.length());//对路径进行截取,获得的路径前边会多加一个杠
3、建立连接的关键代码如下,其中connection = DriverManager.getConnection(url,null,"123456")这句代码中的123456就是数据库的密码。
protected Connection connection; public void openConnection() throws Exception { try { if (connection == null || connection.isClosed()) { String path = this.getClass().getResource("/").getPath().replaceAll("%20"," ");//replaceAll方法是为了解决路径中含有空格字符的问题 path = path.substring(1,path.length());//对路径进行截取,获得的路径前边会多加一个杠 Class.forName("net.ucanaccess.jdbc.UcanaccessDriver"); String url = "jdbc:ucanaccess://"+path+"student.mdb"; connection = DriverManager.getConnection(url,null,"123456"); } } catch (ClassNotFoundException e) { System.out.println("连接失败!"); throw e; } catch (SQLException e) { throw e; } }
4、注意事项:此处使用的是ucanaccess 5.0.1版本,而网上介绍的使用其他版本时需要新建JackcessOpener类的方式不同,该版本不需要新建JackcessOpener类。
浙公网安备 33010602011771号