|
- 3. * 初学者请注意:
- 5. * 1:先建立一个access文件a1.mdb,并放在D:\下; * 2:在数据库文件a1.mdb中建立一个表Table1;
- 7. * 3:为Table1添加一列,并插入至少一条记录;
- 8. * 4:本文是一个完整的类,直接拿去运行就可以。
- 9. */
- import java.sql.*;
- public class ConnectAccess {
- 10. public static void main(String args[]) throws Exception {
- 11. ConnectAccess ca=new ConnectAccess();
- 12. ca.ConnectAccessFile();
- 13. ca.ConnectAccessDataSource();
- 14. }
- 15. public void ConnectAccessFile() throws Exception
- 16. {
- 17. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
- 18. /**
- 19. * 直接连接access文件。
- 20. */
- 21. String dbur1 = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=d:\\a1.mdb";
- 22. Connection conn = DriverManager.getConnection(dbur1, "username", "password");
- 23. Statement stmt = conn.createStatement();
- 24. ResultSet rs = stmt.executeQuery("select * from Table1");
- 25. while (rs.next()) {
- 26. System.out.println(rs.getString(1));
- 27. }
- 28. rs.close();
- 29. stmt.close();
- 30. conn.close();
- 31. }
- 32. public void ConnectAccessDataSource()throws Exception {
- 33. Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
- 34. /**
- 35. * 采用ODBC连接方式 如何建立ODBC连接?
- 36. * 答:在windows下,【开始】->【控制面板】->【性能和维护】->【管理工具】->【数据源】,在数据源这里添加一个指向a1.mdb文件的数据源。
- 37. * 比如创建名字为dataS1
- 38. */
- 39. String dbur1 = "jdbc:odbc:dataS1";// 此为ODBC连接方式
- 40. Connection conn = DriverManager.getConnection(dbur1, "username", "password");
- 41. Statement stmt = conn.createStatement();
- 42. ResultSet rs = stmt.executeQuery("select * from Table1");
- 43. while (rs.next()) {
- 44. System.out.println(rs.getString(1));
- 45. }
- 46. rs.close();
- 47. stmt.close();
- 48. conn.close();
- 49. }
- 50. }
复制代码
|
|