使用 JDBC 类型 1 驱动连接到 Access 数据库

原文:https://www.studytonight.com/java/connecting-to-access.php

使用 JDBC-ODBC 桥(类型 1)驱动将 Java 应用与 Access 数据库连接起来。您需要遵循以下步骤。

注意:在 Java 8 中,JDBC-ODBC 桥已经被移除。不再支持它。

创建 DSN 名称

  1. Go to control panel

    Connecting to access

  2. Go to Administrative tools

    Connecting to access

  3. Select Data Source(ODBC)

    Connecting to access

  4. Add new DSN name, select add

    Connecting to access

  5. Select Access driver from the list, click on finish

    Connecting to access

  6. Give a DSN name, click ok

    Connecting to access

注意:这里我们展示了这个在 Window 7 os 中创建 DSN 的例子。对于其他操作系统,你需要做一些小的改动。

是时候举个例子了!

我们假设您已经在 access 数据库中创建了一个具有 sid 和名称列名的学生表。

import java.sql.*;
class Test
{
  public static void main(String []args)
  {
    try{
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      Connection con = DriverManager.getConnection("jdbc:odbc:Test", "", "");
      Statement s=con.createStatement();        //creating statement

      ResultSet rs=s.executeQuery("select * from student");     //executing statement

      while(rs.next()){
         System.out.println(rs.getInt(1)+" "+rs.getString(2));
      }

      con.close();      //closing connection

    }
    catch(Exception e)
    {
       e.printStackTrace();
    }
  }
}