解析【.mdb】文件

有一些项目用的是微软的access软件,这里面存放数据用的是mdb结尾的文件
有的时候,客户想开发一个新的系统,但是数据需要从这些文件中获取,因此得解析这些文件,来提取数据

一、解析时用到的依赖

1.在项目的pom.xml文件里面添加该依赖

点击查看代码
<!--测试解析.mdb文件-->
        <dependency>
            <groupId>net.sf.ucanaccess</groupId>
            <artifactId>ucanaccess</artifactId>
            <version>5.0.1</version>
        </dependency>

二、一共用到三个方法

1.解析.mdb文件中的所有表名并组装成list返回

代码如下:

点击查看代码
/**
     * 1.该方法解析.mdb文件中的所有表名并组装成list返回
     * @param
     * @return
     */
    public List<String> getAllTables(File file,String password) {
         List<String> list=new ArrayList<>();
        try {
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
            String dbURL = "jdbc:ucanaccess://" + file;
            Properties prop = new Properties();
            prop.put("charSet", "UTF-8");
            prop.put("user", "");//用户名可以是空字符串
            prop.put("password", password);//必须使用密码
            Connection conn = DriverManager.getConnection(dbURL, prop);
            System.out.println(conn);
            DatabaseMetaData metadata = conn.getMetaData();
            ResultSet tables = metadata.getTables(null, null, "%", null);
            while (tables.next()) {
                String table = tables.getString(3);
                list.add(table);
            }
            System.out.println(list);
            tables.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

2.根据sql语句解析指定数据表中的数据并返回

代码如下:

点击查看代码
/**
     * 2.该方法根据sql语句解析指定数据表中的数据并返回
     * @param
     * @param mdbSql
     * @param username
     * @param password
     * @return
     * @throws Exception
     */
    public Map<String, Object> resolverMdb(File file, String mdbSql, String username, String password) throws Exception {
        if (file.exists() || mdbSql.isEmpty()) {
            throw new Exception("mdb文件路径不能为空或者SQL语句不能为空或者返回字段列表不能为空");
        }
        Map<String, Object> mdbEntityList = new HashMap<>();
        Properties prop = new Properties();
        //设置编码
        prop.put("charSet", "UTF-8");
        prop.put("user", username);//用户名可以是空字符串
        prop.put("password", password);//必须使用密码
        //数据地址
        String dbUrl = "jdbc:ucanaccess://" + file;
        //引入驱动
        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver").newInstance();
        try {
            //连接数据库资源
            Connection conn = DriverManager.getConnection(dbUrl, prop);
            //建立查询事务
            Statement statement = conn.createStatement();
            //执行查询
            ResultSet result = statement.executeQuery(mdbSql);
            ResultSetMetaData metaData = result.getMetaData();
            int count = metaData.getColumnCount();
            List<String> mdbColumnList = new ArrayList<String>(count);
            //动态解析字段名
            for (int i = 1; i <= count; i++) {
                mdbColumnList.add(metaData.getColumnName(i));
            }
            //解析执行结果
            while (result.next()) {
                StringBuffer sb = new StringBuffer();
                for (String col : mdbColumnList) {
                    sb.append(col + "==" + result.getObject(col)).append("\t");
                    mdbEntityList.put(col, result.getObject(col));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回数据
        return mdbEntityList;
    }

3.对上面两个方法进行了封装,用户只需提供.mdb文件+文件密码即可查询出数据

代码如下:

点击查看代码
/**
     * 3.该方法对上面两个方法进行了封装,用户只需提供.mdb文件+文件密码即可查询出数据
     * @param
     * @return 测试文件密码----【hp2730】
     * @throws Exception
     */
    @PostMapping("/mdb_list")
    @ApiOperation("解析mdb文件")
    public  List<Map<String, Object>> getResultList(@RequestParam("file") MultipartFile multipartFile,@RequestParam("password") String password) throws Exception {
        List<Map<String, Object>> resultList = new ArrayList<>();
        //MultipartFile转file
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file=File.createTempFile(filename[0], filename[1] + ".");
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<String> allTables = this.getAllTables(file,password);
        if (allTables.size()>0){
            for (String table:allTables) {
                Map<String, Object> map;
                String mdbSql="SELECT * FROM "+table;
                map= this.resolverMdb(file, mdbSql, "", password);
                //把map中为null的数据赋值
                map.forEach((key,value)->{
                    if (value==null){
                        map.put(key,"");
                    }
                });
                map.put("table",table);
                resultList.add(map);
                //数据存库--这块根据实际情况来写,这里只是示例
                //int count=mdbDataDao.getCountByTable(table);
                //if (count>0){
                //    mdbDataDao.deleteByTable(table);
                //}
                //String json = JSON.toJSONString(map);
                //MdbDataEntity mdbDataEntity = new MdbDataEntity();
                //mdbDataEntity.setData(json);
                //mdbDataEntity.setDataly(table);
                //mdbDataEntity.setCreateDate(new Date());
                //mdbDataDao.insert(mdbDataEntity);
                //log.info("数据存库成功!");
            }
        }
        log.info("解析集合"+resultList);
        return resultList;
    }

4.完整代码

点击查看代码
package cn.itCast.manor.modules.test;

import cn.itCast.manor.modules.test.xmljx.Dom4JUtils;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.*;
import java.util.Date;
import java.util.*;

/**
 * @Classname ceshi1
 * @Description:
 * @Date: 2022/12/13 0013 12:02
 * @AUTHOR: 无泪之城
 * @Version 1.0
 */
@RestController
@RequestMapping("test")
@Api(tags="mdb文件解析")
@Slf4j
public class ceshi2 {

    private MdbDataDao mdbDataDao;

    @Autowired
    public void setMdbDataDao(MdbDataDao mdbDataDao) {
        this.mdbDataDao = mdbDataDao;
    }

    /**
     * 1.该方法解析.mdb文件中的所有表名并组装成list返回
     * @param
     * @return
     */
    public List<String> getAllTables(File file,String password) {
         List<String> list=new ArrayList<>();
        try {
            Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
            String dbURL = "jdbc:ucanaccess://" + file;
            Properties prop = new Properties();
            prop.put("charSet", "UTF-8");
            prop.put("user", "");//用户名可以是空字符串
            prop.put("password", password);//必须使用密码
            Connection conn = DriverManager.getConnection(dbURL, prop);
            System.out.println(conn);
            DatabaseMetaData metadata = conn.getMetaData();
            ResultSet tables = metadata.getTables(null, null, "%", null);
            while (tables.next()) {
                String table = tables.getString(3);
                list.add(table);
            }
            System.out.println(list);
            tables.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 2.该方法根据sql语句解析指定数据表中的数据并返回
     * @param
     * @param mdbSql
     * @param username
     * @param password
     * @return
     * @throws Exception
     */
    public Map<String, Object> resolverMdb(File file, String mdbSql, String username, String password) throws Exception {
        if (file.exists() || mdbSql.isEmpty()) {
            throw new Exception("mdb文件路径不能为空或者SQL语句不能为空或者返回字段列表不能为空");
        }
        Map<String, Object> mdbEntityList = new HashMap<>();
        Properties prop = new Properties();
        //设置编码
        prop.put("charSet", "UTF-8");
        prop.put("user", username);//用户名可以是空字符串
        prop.put("password", password);//必须使用密码
        //数据地址
        String dbUrl = "jdbc:ucanaccess://" + file;
        //引入驱动
        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver").newInstance();
        try {
            //连接数据库资源
            Connection conn = DriverManager.getConnection(dbUrl, prop);
            //建立查询事务
            Statement statement = conn.createStatement();
            //执行查询
            ResultSet result = statement.executeQuery(mdbSql);
            ResultSetMetaData metaData = result.getMetaData();
            int count = metaData.getColumnCount();
            List<String> mdbColumnList = new ArrayList<String>(count);
            //动态解析字段名
            for (int i = 1; i <= count; i++) {
                mdbColumnList.add(metaData.getColumnName(i));
            }
            //解析执行结果
            while (result.next()) {
                StringBuffer sb = new StringBuffer();
                for (String col : mdbColumnList) {
                    sb.append(col + "==" + result.getObject(col)).append("\t");
                    mdbEntityList.put(col, result.getObject(col));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回数据
        return mdbEntityList;
    }

    /**
     * 3.该方法对上面两个方法进行了封装,用户只需提供.mdb文件+文件密码即可查询出数据
     * @param
     * @return 测试文件密码----【hp2730】
     * @throws Exception
     */
    @PostMapping("/mdb_list")
    @ApiOperation("解析mdb文件")
    public  List<Map<String, Object>> getResultList(@RequestParam("file") MultipartFile multipartFile,@RequestParam("password") String password) throws Exception {
        List<Map<String, Object>> resultList = new ArrayList<>();
        //MultipartFile转file
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file=File.createTempFile(filename[0], filename[1] + ".");
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<String> allTables = this.getAllTables(file,password);
        if (allTables.size()>0){
            for (String table:allTables) {
                Map<String, Object> map;
                String mdbSql="SELECT * FROM "+table;
                map= this.resolverMdb(file, mdbSql, "", password);
                //把map中为null的数据赋值
                map.forEach((key,value)->{
                    if (value==null){
                        map.put(key,"");
                    }
                });
                map.put("table",table);
                resultList.add(map);
                //数据存库
                int count=mdbDataDao.getCountByTable(table);
                if (count>0){
                    mdbDataDao.deleteByTable(table);
                }
                String json = JSON.toJSONString(map);
                MdbDataEntity mdbDataEntity = new MdbDataEntity();
                mdbDataEntity.setData(json);
                mdbDataEntity.setDataly(table);
                mdbDataEntity.setCreateDate(new Date());
                mdbDataDao.insert(mdbDataEntity);
                log.info("数据存库成功!");
            }
        }
        log.info("解析集合"+resultList);
        return resultList;
    }

三、测试时用到的mdb文件

链接 密码
https://wwuh.lanzout.com/i4bSz0inshvi 9jq8
posted @ 2022-12-14 15:05  青喺半掩眉砂  阅读(388)  评论(0编辑  收藏  举报