问题描述
下面是连接Access的代码import java.sql.*;public class Test{ public static void main(String args[]) { Connection con; Statement stmt; ResultSet rs; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(ClassNotFoundException e) { System.out.println(""+e); } try { con=DriverManager.getConnection("jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=D:123data.mdb","",""); stmt=con.createStatement(); rs=stmt.executeQuery("select * from info"); while(rs.next()) { String title=rs.getString(2); System.out.print(" title:"+title+"t"); } con.close(); } catch(SQLException e) {System.out.println(e);} } } 我想把它改成相对路径,即DBQ中不用绝对路径。让当前程序能找到data.mdb,那么这个语句该怎么写。帮忙修改一下连data.mdb的语句,谢谢! 问题补充:jcyanfan 写道
解决方案
给楼主一个完整的例子吧:假设abc.mdb放到data子目录下边:package mytest.db.access;import java.sql.*;public class TestAccess{ public static void main(String args[]) { Connection con; Statement stmt; ResultSet rs; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException e) { System.out.println("" + e); } try { String path = TestAccess.class.getClassLoader().getResource("data\abc.mdb").getPath() .substring(1); path = java.net.URLDecoder.decode(path); System.out.println(path); con = DriverManager.getConnection( "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=" + path, "", ""); stmt = con.createStatement(); rs = stmt.executeQuery("select 1"); while (rs.next()) { String title = rs.getString(1); System.out.print(" title:" + title + "t"); } con.close(); } catch (SQLException e) { System.out.println(e); } }}
解决方案二:
String path = this.getClass().getClassLoader().getResource("123data.mdb").getPath().substring(1);con=DriverManager.getConnection("jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ="+path,"","");