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 驱动程序管理器] 未发现数据源名称并且未指定默认驱动程序
试试这个:
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); } }
谢谢,对比你的代码,发现原来是我驱动名写得不规范,空格不能乱加,乱省。
Microsoft Access Driver (*.mdb) != Microsoft Access Driver(*.mdb)
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") != Class.forName("sun.jdbc.odbc.JdbcOdbcDriver ")