使用Java访问MS Access数据库

时间:2013-07-19 09:44:23

标签: ms-access jdbc odbc

            try{
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                String database = 
          "jdbc:odbc:Driver={MS Access Database (*.accdb)};DBQ=obn.accdb;";
        c= DriverManager.getConnection(database, "", "");
        s=c.createStatement();
                    string = "IN TRY";
                    s.close();  // Close the statement
                    c.close(); // Close the database. Its no more required
                    JOptionPane.showMessageDialog( null, string );

            }
            catch(Exception e)
            {
                string = "IN exception";
                JOptionPane.showMessageDialog( null, string );
            }

我尝试使用Java使用上述代码访问MS Access数据库时总是有异常。我尝试了一些事情

            c= DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=obn.mdb");
            s=c.createStatement();

在第一个和第二个我得到例外 -

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified. 

...

                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        c= DriverManager.getConnection("jdbc:odbc:obn");
        s=c.createStatement();

尝试这样做,在Windows中的ODBC数据源(32位)中添加OBN,选择数据库的路径。但它也没有用。

它给出了错误

The specified DSN contains an architecture mismatch between the Driver and Application

我通常不使用MS Access,但我必须参加大学项目

2 个答案:

答案 0 :(得分:1)

验证您是否为您的环境使用了正确的ODBC驱动程序名称。您需要指定...

{Microsoft Access Driver (*.mdb)}

...或...

{Microsoft Access Driver (*.mdb, *.accdb)}

...取决于您是否要使用较旧的“Jet”驱动程序(仅适用于.mdb文件,仅适用于32位应用程序)或较新的“ACE”驱动程序(.mdb或.accdb文件,可以如果机器上没有Access,则可能需要单独安装32位或64位应用程序。

答案 1 :(得分:0)

我找到了解决方案。

使用此连接是正确的。 c = DriverManager.getConnection(“jdbc:odbc:obn”); 必须在Windows管理工具中的odbc下添加数据库。由于没有64位驱动程序,因此必须使用32位驱动程序。由于使用了3​​2位odbc驱动程序,我们无法使用64位JVM,因此从项目管理器将JVM从64位更改为32位可以解决问题,现在它可以正常工作