Home Java javaTutorial In-depth analysis of Sqlite multi-threaded database issues

In-depth analysis of Sqlite multi-threaded database issues

Dec 19, 2016 pm 02:44 PM

今天经理给了我一个三十多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"))); 
    } 
}
Copy after login

 以上就是深入Sqlite多线程入库的问题的内容,更多相关内容请关注PHP中文网(www.php.cn)! 


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to create a user login system using PHP and SQLite How to create a user login system using PHP and SQLite Jul 28, 2023 pm 09:27 PM

How to create a user login system using PHP and SQLite In today's Internet era, a user login system is one of the basic functions of many websites and applications. This article will introduce how to create a simple and powerful user login system using PHP and SQLite. SQLite is an embedded database engine. It is a zero-configuration, server-side database engine. PHP is a popular server-side scripting language that can be used in conjunction with SQLite to create a flexible and efficient user login system. by

Implementing user permissions and access control using PHP and SQLite Implementing user permissions and access control using PHP and SQLite Jul 29, 2023 pm 02:33 PM

Implementing user permissions and access control using PHP and SQLite In modern web applications, user permissions and access control are a very important part. With proper permissions management, you can ensure that only authorized users can access specific pages and functions. In this article, we will learn how to implement basic user permissions and access control using PHP and SQLite. First, we need to create a SQLite database to store information about users and their permissions. The following is the structure of a simple user table and permission table

PHP and SQLite: How to do data compression and encryption PHP and SQLite: How to do data compression and encryption Jul 29, 2023 am 08:36 AM

PHP and SQLite: How to Compress and Encrypt Data In many web applications, data security and storage space utilization are very important considerations. PHP and SQLite are two very widely used tools, and this article will introduce how to use them for data compression and encryption. SQLite is a lightweight embedded database engine that does not have a separate server process but interacts directly with applications. PHP is a popular server-side scripting language that is widely used to build dynamic

Data charting and visualization using PHP and SQLite Data charting and visualization using PHP and SQLite Jul 28, 2023 pm 01:01 PM

Using PHP and SQLite to implement data charts and visualization overview: With the advent of the big data era, data charts and visualizations have become an important way to display and analyze data. In this article, we will introduce how to use PHP and SQLite to implement data charts and visualization functions. Take an example as an example to show how to read data from a SQLite database and use a common data chart library to display the data. Preparation: First, you need to ensure that PHP and SQLite databases have been installed. If it is not installed, you can

Create a simple blog: using PHP and SQLite Create a simple blog: using PHP and SQLite Jun 21, 2023 pm 01:23 PM

With the development of the Internet, blogs have become a platform for more and more people to share their lives, knowledge and ideas. If you also want to create a blog of your own, then this article will introduce how to use PHP and SQLite to create a simple blog. Determine the needs Before starting to create a blog, we need to determine the functions we want to achieve. For example: Create a blog post Edit a blog post Delete a blog post Display a list of blog posts Display blog post details User authentication and permission control Install PHP and SQLite We need to install PHP and S

PHP and SQLite: How to deal with long connections and disconnection and reconnection PHP and SQLite: How to deal with long connections and disconnection and reconnection Jul 29, 2023 am 09:05 AM

PHP and SQLite: How to deal with long connections and disconnection and reconnection Introduction: In web development, PHP and SQLite are two commonly used technologies. However, long connections and disconnection and reconnection are some of the problems often encountered when using PHP and SQLite. This article will introduce how to handle the problems of long connections and disconnection and reconnection in PHP, and provide some example codes to help developers better understand and solve these problems. 1. Persistent connection problem When using PHP to connect to SQLite database, long connection (Persis

How to use PHP and SQLite for full-text search and indexing strategies How to use PHP and SQLite for full-text search and indexing strategies Jul 29, 2023 pm 08:45 PM

How to use PHP and SQLite for full-text search and indexing strategies Introduction: In modern application development, full-text search capabilities are indispensable in many fields. Whether on blogs, news websites, or e-commerce platforms, users are accustomed to using keywords to search. Therefore, to improve user experience and provide better search results, we need to provide full-text search capabilities using appropriate search and indexing strategies. In this article, we will explore how to use PHP and SQLite databases to implement full-text search and

How to import and export data using PHP and SQLite How to import and export data using PHP and SQLite Jul 28, 2023 am 11:43 AM

How to Import and Export Data Using PHP and SQLite Importing and exporting data is one of the common tasks while developing a website or application. Using PHP and SQLite, we can easily import data from external files into SQLite database and export data from database to external files. This article will introduce how to use PHP and SQLite to import and export data, and provide corresponding code examples. Data import First, we need to prepare an external file containing the data to be imported. this file

See all articles