深入Sqlite多線程入庫的問題_java

來源:互聯網
上載者:User
今天經理給了我一個三十多M的sql檔案,讓我測試資料定位的問題。按照慣例,我使用navicat for sqlite建立一個表,然後將sql檔案匯入。我然後去幹其他事兒了,大約過了一個多小時,我想資料應該匯入的差不多了吧。我開啟一看,汗,死在那兒了。我關掉軟體又重新匯入一遍,還是那個德行。又得知經理曾經自己也導過,沒有成功。看來,用工具匯入的方法行不通了。

但是,想想就十多萬條資料,就是十多萬條insert sql語句,有那麼難嗎?於是,我想還是自己寫一個程式匯入吧。雖然中間也遇到一些小插曲,但是還是成功地把資料導進去了。
程式的代碼如下:
複製代碼 代碼如下:

package com.geoway.pad.common.tool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
 * @author likehua
 * @note   SQLite建庫以及批量入庫
 * */
public class BatchTool{
    //ddl  
    private static String ddl="CREATE TABLE IF NOT EXISTS pbeijing_point (OBJECTID  INTEGER,NAME  TEXT,ADDRESS  TEXT,PHONE TEXT,FAX  TEXT,TYPE TEXT,CITYCODE TEXT,URL  TEXT,EMAIL  TEXT,NAME2  TEXT,X  INTEGER,Y  INTEGER)";
    Connection jCon=null;
    //get connection
    public synchronized Connection  getConnection(){    
        if(jCon==null){
//          json=
                Statement state=null;
                try {
                    Class.forName("org.sqlite.JDBC");
                    jCon=DriverManager.getConnection("jdbc:sqlite:c:\\newD.db");
                    state=jCon.createStatement();
                    state.executeUpdate(ddl);                   
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
        }
        return jCon;
    }
    //建立500個線程
    ExecutorService  service=Executors.newFixedThreadPool(500);
    //讀取sql檔案     每五百個insert 語句由一個線程大量操作  
    public  void   readBatchSQL(InputStream is) throws IOException{
        BufferedReader bufferReader=new BufferedReader(new InputStreamReader(is,"UTF-8"));
        String line;
        String one="";
        int tag=0;
        String  batchSql="";
        while((line=bufferReader.readLine())!=null){
            one+=line;
            if(one.indexOf(";")!=-1){
                batchSql+=one;
                one="";//reset
                tag++;
            };
            //符合條件   開闢一個線程
            if(tag!=0&&tag/500!=0){
                service.execute(new SQLiteBatchHandler(batchSql));
                batchSql="";//reset
                tag=0;//reset
            }           
        }
        //最後執行 剩餘的sql
        if(batchSql.length()>0){
            System.out.println("finalSQL:"+batchSql);
            Runnable r=new SQLiteBatchHandler(batchSql);
            service.execute(r);
        };
        try {
            //關閉線程池
            this.service.shutdown();            
        this.service.awaitTermination(1, TimeUnit.HOURS);<BR>                getConnection().close();<BR>       } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    };
    /**
     * @note  分割sql
     * */
    private static String[] splitSQL(String batchSQl){
        if(batchSQl!=null){
            return batchSQl.split(";");
        };
        return null;
    }
    /**
     * @note  執行批次更新操作
     *        由於connection.comit 操作時   如果存在 statement沒有close  就會報錯   因此將此方法加上同步    。
     * */
    private  synchronized  void  exucteUpdate(String batch){
        Statement ste=null;
        Connection con=null;
        try{
        con=getConnection();
        con.setAutoCommit(false);
        ste=con.createStatement();
        String[] sqls=this.splitSQL(batch);
        for(String sql:sqls){
            if(sql!=null){
                ste.addBatch(sql);
            };
        };
        ste.executeBatch();<BR>                ste.close();
        con.commit();//提交       
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("執行失敗:"+batch);
            try {
                con.rollback();//復原
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally{
            if(ste!=null){
                try {
                    ste.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * @author likehua
     * @note   入庫線程
     * */
    private  class SQLiteBatchHandler implements Runnable{
        private String batch;
        public  SQLiteBatchHandler(String sql){
            this.batch=sql;
        };
        @SuppressWarnings("static-access")
        @Override
        public void run() {         
            try {
                Thread.currentThread().sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(this.batch.length()>0){
                exucteUpdate(batch);

            };

        }       
    }
    /**
     * @author likehua
     * @note   主函數入口
     * */
    public  static  void main(String[] args) throws FileNotFoundException, IOException{
        BatchTool s=new BatchTool();
        s.readBatchSQL(new FileInputStream(new File("c:\\poi.sql")));
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.