首页 > 数据库 >java8读取Access数据库

java8读取Access数据库

时间:2023-03-22 12:34:03浏览次数:60  
标签:String mdb mdbPath Access add mdbList mdbSql java8 读取

    添加pom配置文件

<dependency>
    <groupId>net.sf.ucanaccess</groupId>
    <artifactId>ucanaccess</artifactId>
    <version>4.0.4</version>
</dependency>

 

    封装工具类

package com.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;

/**
 * @author xuan
 * @since 2020-08-21
 * 读取mdb文件
 */
public class MdbUtil {

    /**
     *
     * @param mdbPath mdb文件路径
     * @param mdbSql mdb执行sql
     * @param mdbColumnList mdb查询字段
     * @return
     * @throws Exception
     */
    public static List<Map<String, Object>> resolverMdb(String mdbPath, String mdbSql, List<String> mdbColumnList) throws Exception {
        if (mdbPath.isEmpty() || mdbSql.isEmpty() || mdbColumnList.isEmpty()) {
            throw new Exception("mdb文件路径不能为空或者SQL语句不能为空或者返回字段列表不能为空");
        }
        List<Map<String, Object>> mdbEntityList = new ArrayList<>();
        Properties prop = new Properties();
        //设置编码
        prop.put("charSet", "UTF-8");
        //数据地址
        String dbUrl = "jdbc:ucanaccess://" + mdbPath;
        //引入驱动
        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver").newInstance();
        try {
            //连接数据库资源
            Connection conn = DriverManager.getConnection(dbUrl, prop);
            //建立查询事务
            Statement statement = conn.createStatement();
            //执行查询
            ResultSet result = statement.executeQuery(mdbSql);
            //解析执行结果
            Map<String, Object> mdbMapList = new HashMap<>(16);
            while (result.next()) {
                for (String col : mdbColumnList) {
                    mdbMapList.put(col, result.getObject(col));
                }
                mdbEntityList.add(mdbMapList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回数据
        return mdbEntityList;
    }

    public static void main(String[] args) throws Exception {
        String mdbPath = "D://data//slsm_in.mdb";
        String mdbSql = "SELECT * FROM AlternateUnit";
        List<String> mdbList = new ArrayList<>();
        mdbList.add("UNID");
        mdbList.add("AUNID");
        mdbList.add("PRI");
        mdbList.add("NOTE");
        List<Map<String, Object>> list = MdbUtil.resolverMdb(mdbPath, mdbSql, mdbList);
        System.out.println(list);
    }
} 

 

标签:String,mdb,mdbPath,Access,add,mdbList,mdbSql,java8,读取
From: https://www.cnblogs.com/pxuan/p/17243288.html

相关文章