使用java访问Access数据库的方法
[1].[代码] [Java]代码
01 |
try { |
02 |
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ); |
03 |
String url = "jdbc:odbc:Driver={Microsoft Access Driver " + |
04 |
"(*.mdb, *.accdb)};DBQ=C:\\Database\\Northwind 2007.accdb" ; |
05 |
Connection con = DriverManager.getConnection(url); |
06 |
System.out.println( "Connected!" ); |
07 |
con.close(); |
08 |
} catch (SQLException e) { |
09 |
System.out.println( "SQL Exception: " + e.toString()); |
10 |
} catch (ClassNotFoundException cE) { |
11 |
System.out.println( "Class Not Found Exception: " + cE.toString()); |
12 |
} |
[2].[代码] 带密码的访问
01 |
static class MyConnention{ |
02 |
public static Connection getConnection() throws Exception{ |
03 |
/**配置数据源后*/ |
04 |
//String URL="jdbc:odbc:<MS Access Database配置数据源名称>"; |
05 |
//Connection c=DriverManager.getConnection(URL,"",""); |
06 |
/**不配置数据源*/ |
07 |
//jdbc:odbc:DRIVER={Microsoft Access Driver<此处必须有空格 >(*.mdb,<注意此处必须有一空格>*.accdb)};DBQ=<数据库名称路径>[;pwd=password] |
08 |
String url1= "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=f:/data/db1.accdb;pwd=qing" ; |
09 |
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ).newInstance(); |
10 |
Connection c=DriverManager.getConnection(url1); |
11 |
return c; |
12 |
} |
13 |
} |
[3].[代码] 使用相对路径
01 |
static class MyConnention{ |
02 |
public static Connection getConnection() throws Exception{ |
03 |
/**不配置数据源*/ |
04 |
//jdbc:odbc:DRIVER={Microsoft Access Driver<此处必须有空格 >(*.mdb,<注意此处必须有一空格>*.accdb)};DBQ=<数据库名称路径>[;pwd=password] |
05 |
Class theClass=MyConnention. class ; |
06 |
java.net.URL u= theClass.getResource( "db/db1.accdb" ); |
07 |
String url=u.getPath().substring( 1 ,u.getPath().length()).replaceAll( "%20" , " " ); |
08 |
String url1= "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" +url+ ";pwd=qing" ; |
09 |
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ).newInstance(); |
10 |
Connection c=DriverManager.getConnection(url1); |
11 |
return c; |
12 |
} |
13 |
} |