Java通过JDBC和ODBC桥接来访问Access文件

这次做的系统有输入和输出为MDB(Access)文件,在网上找了一下,可以用JDBC和ODBC桥接来实现Access文件的访问。测试代码如下:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class Test {
    static Connection connection;
    static Statement statement;
    public static void main(String[] args) {
        String mdbFile = "C:\TEST.mdb";
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
            String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + mdbFile;
            connection = DriverManager.getConnection( database ,"","");
            buildStatement();
            executeQuery();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void buildStatement() throws SQLException {
        statement = connection.createStatement();
    }
    public static void executeQuery() throws SQLException {
        boolean foundResults = statement.execute("SELECT * FROM TEST");
        if (foundResults) {
            ResultSet set = statement.getResultSet();
            if(set != null) displayResults(set);
        } else {
            connection.close();
        }
    }
    public static void displayResults(ResultSet rs) throws SQLException {
        ResultSetMetaData metaData = rs.getMetaData();
        int columns = metaData.getColumnCount();
        StringBuilder text = new StringBuilder();
        while (rs.next()) {
            for (int i = 1; i <= columns; ++i) {
                text.append(metaData.getColumnName(i));
                text.append(":t");
                text.append(rs.getString(i));
                text.append(" n");
            }
            text.append(" n");
        }
        System.out.println(text.toString());
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注