java操作sqlite

1、下载sqlite的驱动

<!-- sqlite -->
    <dependency>
		<groupId>org.xerial</groupId>
		<artifactId>sqlite-jdbc</artifactId>
		<version>3.8.11.2</version>
	</dependency>


2、sqlite的工具类

/**
 * 
 */
package core.sqlite;

import java.sql.Connection;
import java.sql.DriverManager;

/**
 * Sqllite数据源
 */
public class SqlliteDataSource {

	private Connection conn;
	private String dbFile;
	
	/**
	 * 
	 */
	public SqlliteDataSource() {

	}

	/**
	 * 打开数据源连接
	 * @throws Exception
	 */
	protected synchronized void open() throws Exception{
		if (this.dbFile == null){
			throw new IllegalArgumentException("dbFile cannot be null, please set it.");
		}
		
		Class.forName("org.sqlite.JDBC");
	    this.conn =
	    		DriverManager.getConnection("jdbc:sqlite:" + dbFile);
	}
	
	/**
	 * 关闭数据源连接
	 * @throws Exception
	 */
	protected synchronized void close() throws Exception{
		if (this.conn != null){
			this.conn.close();
			this.conn = null;
		}
	}
	
	/**
	 * 判断是否已连接数据库
	 * @return 
	 */
	public synchronized boolean isConnected(){
		return this.conn != null;
	}

	/**
	 * 数据库文件
	 * @return
	 */
	public String getDbFile() {
		return dbFile;
	}
	
	/**
	 * 设置数据库文件
	 * @param dbFile
	 */
	public void setDbFile(String dbFile) {
		this.dbFile = dbFile;
	}
	
	/**
	 * 获取数据库连接
	 * @return
	 */
	protected Connection getConnection(){
		return this.conn;
	}
}



3、例子

package core.sqlite;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

public class SqliteTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String dbFile = "E:\\其他\\mysqlite.db";
		SqlliteDataSource sqllite = new SqlliteDataSource();
		sqllite.setDbFile(dbFile);
		

		try {
			Date date1= new Date();
			
			sqllite.open();
			
			Connection conn = sqllite.getConnection();
			
			String sql = "insert into TABLE_TEST (NAME) values('张三');";
			StringBuilder sb = new StringBuilder();
			for(int i=0;i<100;i++){
				//sqllite_state.execute("insert into TABLE_TEST (NAME) values('张三');");
				sb.append(sql);
				System.out.println(i+":"+sql);
			}
			
			Statement sqllite_state = conn.createStatement();
			
			//sqllite_state.execute();//只用于查询语句,返回集合的,用于insert、update、delete是错误的
			sqllite_state.executeUpdate(sb.toString());//只用于insert、update、delete,不能用于select
			
			sqllite.close();
			
			Date date2= new Date();
			System.out.println("执行完毕,用时:"+(date2.getTime()-date1.getTime())/1000);
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值