常用工具类------读取文件数据到数据库

本文介绍了一种将Excel和TXT文件中的数据导入数据库的方法。通过Java实现,文章提供了详细的代码示例,包括如何读取文件内容、建立数据库连接以及执行批量插入等关键步骤。

 第一次写博客,请多多指教!!!

 將excel数据导入数据库

public void readExcel(String filePath,String jdbcPath,String insertRow,
             String dbName,String dbPwd) {   
         
          //读取文件来源.   
          File importExcel = new File(filePath);   
          try{   
              //数据库连接  
              Connection conn = this.getConnection(jdbcPath,dbName,dbPwd);
              PreparedStatement prep = conn.prepareStatement(insertRow);   
              
              //首先是获取文件,也就是上面的Excel文件,这里是或者这个Excel文件.   
              Workbook workBook = Workbook.getWorkbook(importExcel);   
                
              //其次就是获取这个Excel文件的工作表格.这里就基本处理,当然可以不用数组形式,因为只有第一个工作表格有数据,其他两个没有,     
              Sheet[] sheet = workBook.getSheets();    
                                     
              int sheet_i_num = 0;//获取工作表格的行数   

              if(sheet!=null&&sheet.length>0){//判断一下   
                 for(int sheetNum=0;sheetNum < sheet.length; sheetNum++){//获得有多少个工作表格,对每一个操作.   
                      //读取工作表格有多少行   
                      sheet_i_num = sheet[sheetNum].getRows();   
                        
                      //取数据,此处从rowNum = 1开始   
                      for(int rowNum = 1; rowNum < sheet_i_num ; rowNum++){   
                          //对每一个单元格进行操作.   
                          Cell[]   cells = sheet[sheetNum].getRow(rowNum); 
                          //数据是取到了,然后就是直接插入到数据库当中了,
                          for(int j=0;j<cells.length;j++){
                              prep.setString(j+1, cells[j].getContents());  
                          }                               
                          prep.executeUpdate();     
                      }   
                  }                    
              }
              System.out.println("操作成功");
              workBook.close();   
              prep.close();   
              conn.close();   
          }catch(Exception e){   
              System.out.println(e.getMessage());   
          }   
      }

将txt文档数据导入数据库

public void readFile(String filePath,String jdbcPath,String insertRow,
             String dbName,String dbPwd)throws SQLException, FileNotFoundException {
         
         //读取源文件
         File importFile = new File(filePath);
         try {
             String lineTXT = null;
             InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(importFile),"GBK");
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader, 1024);
             Connection conn = this.getConnection(jdbcPath,dbName,dbPwd);
             PreparedStatement prep = conn.prepareStatement(insertRow);
             while ((lineTXT = bufferedReader.readLine()) != null) {
                 String[] temp = null;
                 temp = lineTXT.split("\t");
                 int count = 0;// 计数器
                  
                 conn.setAutoCommit(false);// 设置数据手动提交,自己管理事务
                 for(int j=0;j<temp.length;j++){
                     prep.setString(j+1, temp[j]);
                 }
                 prep.addBatch();// 用PreparedStatement的批量处理 
                 if (count % 2000 == 0) {// 当增加了500个批处理的时候再提交
                     prep.executeBatch();// 执行批处理
                 }
             }
             conn.commit();
             bufferedReader.close();
             prep.close();
             conn.close();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }

链接数据库

public static Connection getConnection(String jdbcPath,String dbName,String dbPwd) {
         
         String encoding = "utf-8";
         Connection conn = null;
         try {
             Class.forName("com.mysql.jdbc.Driver");
         } catch (ClassNotFoundException e) {
             e.printStackTrace();
         }
         try {
             conn = DriverManager.getConnection(jdbcPath, dbName, dbPwd);
         } catch (SQLException e) {
             e.printStackTrace();
         }
         return conn;
     }

 

测试类

public class ImportTest {
    
    @Test
    public static void main(String[] args){
        ImportData data = new ImportData();
        String filePath = "D://excel.txt";
        String jdbcPath = "jdbc:mysql://172.16.0.3:3306/innovation?characterEncoding=utf-8";
        String dbName = "root";
        String dbPwd = "123456";
        String insertRow = "insert into innovation_news (title,content,source) values (?,?,?)";
//        data.readExcel(filePath, jdbcPath, insertRow, dbName, dbPwd);
        
        try {
            data.readFile(filePath, jdbcPath, insertRow, dbName, dbPwd);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

 

转载于:https://www.cnblogs.com/hl-wang/p/5623916.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值