首页 新闻 会员 周边 捐助

Jdbc 直连 Access 不成功

1
悬赏园豆:10 [已解决问题] 解决于 2012-05-10 12:16
 2 import java.sql.*;
 3 public class AccessDemo2
 4 {
 5     public static void main(String[] args)
 6     {
 7         Connection conn;
 8         Statement stmt;
 9         ResultSet rs;
10         String url = "jdbc:odbc:driver = {MicroSoft Access Driver(*.mdb)};DBQ=C:\\temp\\mydatabase";
11         try
12         {
13             // 加载JdbcOdbcDriver 驱动
14             Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver "); 
15             
16         }
17         catch (ClassNotFoundException e)
18         {
19             System.out.println("Driver Error "+e);
20         }
21         try
22         {
23             // 通过数据源连接到数据库
24             conn = DriverManager.getConnection(url,"","");
25             stmt = conn.createStatement();
26             rs = stmt.executeQuery("select * from info");
27             while (rs.next())
28             {
29                 System.out.print(rs.getString(1) + " ");
30                 System.out.println(rs.getString(2) + " ");
31                 
32             }
33             
34         rs.close();
35         stmt.close();
36         conn.close();
37         }
38         catch (SQLException e)
39         {
40             System.out.println("Connection Error "+e);
41         }
42     }
43 }

运行结果:

Driver Error java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver
Connection Error java.sql.SQLException: [Microsoft][ODBC 驱动程序管理器] 未发现数据源名称并且未指定默认驱动程序

仰望星空的耕田人的主页 仰望星空的耕田人 | 初学一级 | 园豆:6
提问于:2012-05-09 16:19
< >
分享
最佳答案
1

试试这个:

    public static void ConnAccess() {
        Connection conn;
        Statement stmt;
        ResultSet rs;
        String url = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};Dbq=C:/Email2012.mdb;Uid=Admin;Pwd=;";
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        } catch (ClassNotFoundException e) {
            System.out.println("Driver Error " + e);
        }
        try {
            conn = DriverManager.getConnection(url);
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select top 10  * from EmailDB ");
            while (rs.next()) {
                System.out.print(rs.getString(1) + " ");
                System.out.println(rs.getString(2) + " ");
            }
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            System.out.println("Connection Error:" + e);
        }
    }
收获园豆:10
邀月 | 高人七级 |园豆:25475 | 2012-05-10 08:36

谢谢,对比你的代码,发现原来是我驱动名写得不规范,空格不能乱加,乱省。

Microsoft Access Driver (*.mdb)  != Microsoft Access Driver(*.mdb) 

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") != Class.forName("sun.jdbc.odbc.JdbcOdbcDriver ")
仰望星空的耕田人 | 园豆:6 (初学一级) | 2012-05-10 12:20
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册