In-depth analysis of Sqlite multi-threaded database issues
今天经理给了我一个三十多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"))); } }
以上就是深入Sqlite多线程入库的问题的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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 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 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

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

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 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 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 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
