Java操作SQLite数据库辅助类

本工具类既可以作为基类也可用于直接操作数据库。使用时建议的做法就是。创建UserDao继承自SQLiteHelper即可。


操作Mysql,Orecle,SQL server等数据库替换驱动名极jar就行啦。

package com.hengyi.sqlite_demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SQLiteHelper {
	/**
	 * 创建服务器连接
	 * @return
	 */
	public Connection connection(){
		Connection c = null;
		 try {
		      Class.forName("org.sqlite.JDBC");
		      c = DriverManager.getConnection("jdbc:sqlite:test.db");
		      System.out.println("连接成功");
		 } catch ( Exception e ) {
		      c = null;
		      System.out.println("连接失败");
		 }
		 return c;
	}
	
	
	/**
	 * 执行一条更新
	 * @param sql
	 * @return
	 */
	public boolean executeUpdate(String sql){
		Connection conn = connection();
		Statement stmt = null;
		try{
			stmt = conn.createStatement();
			stmt.executeUpdate(sql);
			
			stmt.close();
			conn.close();
			
			return true;
		}catch(Exception e){
			return false;
		}
	}
	
	
	/**
	 * 查询一条数据
	 * @param sql
	 * @return
	 */
	public Map<String,Object> find(String sql){
		Connection conn = connection();
		Statement stmt = null;
		ResultSet rs = null;
		try{
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			ResultSetMetaData rsm = rs.getMetaData();
			Map<String,Object> data = new HashMap<String,Object>();

			if(rs.next()){
				for (int i = 1; i <= rsm.getColumnCount(); i++) {// 数据库里从 1 开始  
	                String c = rsm.getColumnName(i);  
	                String v = rs.getString(c);  
	                System.out.println(c + ":" + v + "\t");  
	                data.put(c, v);  
	            }  
			}
			
			stmt.close();
			conn.close();
			rs.close();

			return data;
		}catch(Exception e){
			return null;
		}
	}
	
	/**
	 * 查询多条数据
	 * @param sql
	 * @return
	 */
	public List<Map<String,Object>> select(String sql){
		Connection conn = connection();
		Statement stmt = null;
		ResultSet rs = null;
		try{
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			ResultSetMetaData rsm = rs.getMetaData();
			Map<String,Object> data = null;
			List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();

			while(rs.next()){
				data = new HashMap<String,Object>();
				for (int i = 1; i <= rsm.getColumnCount(); i++) {// 数据库里从 1 开始  
	                String c = rsm.getColumnName(i);  
	                String v = rs.getString(c);   
	                data.put(c, v); 
	            }  
				list.add(data);
			}
			
			stmt.close();
			conn.close();
			rs.close();

			return list;
		}catch(Exception e){
			return null;
		}
	}
}

你可能感兴趣的:(Java操作SQLite数据库辅助类)