sqlite 사용 주의사항

최근 sqlite 의 jdbc 사용 조작 을 봉인 하 였 는데 시스템 내부 에서 Satement,ResultSet 등 이 쉽게 닫 히 지 않 고 봉인 이 잘못 되 었 다 는 것 을 알 게 되 었 습 니 다.다음은 제 정확 한 사용 을 공유 하 겠 습 니 다.

package org.liufei.cbook.dbcon;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;

public class SQLiteConn implements Serializable {
	private static final long serialVersionUID = 102400L;

	private DbFile dbfile ;

	public SQLiteConn(DbFile dbfile) {
		super();
		this.dbfile = dbfile;
	}
	
	/**
	 *  SQLite          
	 * @return Connection
	 * @throws Exception
	 */
	public Connection getConnection() throws Exception {
		Connection connection = null ;
		try{
			Class.forName("org.sqlite.JDBC", true, this.getClass().getClassLoader()) ;
			connection = DriverManager.getConnection("jdbc:sqlite:" + dbfile.getDbfilepath());
		}catch (Exception e) {
			throw new Exception("" + e.getLocalizedMessage(), new Throwable("                  。")) ;
		}
		return connection ;
	}
}

그 중에서 org.liufei.cbook.dbcon.dbFile 은 설 정 된 데이터베이스 파일 의 경로 클래스 가 져 오기

package org.liufei.cbook.dbutils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class SQLiteCRUD {

	private Connection connection ;
	public SQLiteCRUD(Connection connection) {
		this.connection = connection ;
	}

	/**
	 *    。
	 * @param sql
	 * @return boolean
	 */
	public boolean createTable(String sql){
		System.out.println(sql);
		Statement stmt = null ;
		try{
			stmt = this.connection.createStatement() ;
			stmt.executeUpdate(sql) ;
			return true ;
		}catch (Exception e) {
			System.out.println("         : " + e.getLocalizedMessage());
			connectionRollback(connection) ;
			return false ;
		}
	}
	
	/**
	 *            。
	 * @param table   
	 * @param params     
	 * @return boolean
	 */
	public boolean insert(String table, String[] params){
		Statement stmt = null ;
		String sql = "insert into " + table  + " values('";
		for(int i = 0 ; i < params.length ;i++){
			if(i == (params.length - 1)){
				sql += (params[i] + "');") ;
			}else{
				sql += (params[i] + "', '") ;
			}
		}
		System.out.println(sql);
		try{
			stmt = this.connection.createStatement() ;
			stmt.executeUpdate(sql) ;
			return true ;
		}catch (Exception e) {
			System.out.println("    " + table + "      : " + e.getLocalizedMessage());
			connectionRollback(connection) ;
			return false ;
		}
	}
	
	/**
	 *            。
	 * @param table   
	 * @param keyParam           
	 * @param keyField              
	 * @param fields              
	 * @param params           
	 * @return boolean
	 */
	public boolean update(String table, String keyParam, String keyField, String[] fields, String[] params){
		Statement stmt = null ;
		String sql = "update " + table + " set " ;
		for(int i = 0 ; i < fields.length ; i++){
			if(i == (fields.length - 1)){
				sql += (fields[i] + "='" + params[i] + "' where " + keyField + "='" + keyParam +"';") ;
			}else{
				sql += (fields[i] + "='" + params[i] + "', ") ;
			}
		}
		System.out.println(sql);
		try{
			stmt = this.connection.createStatement() ;
			stmt.executeUpdate(sql) ;
			return true ;
		}catch (Exception e) {
			System.out.println("   " + table + "      : " + e.getLocalizedMessage());
			connectionRollback(connection) ;
			return false ;
		}
		
	}
	
	/**
	 *              。
	 * @param table
	 * @param key
	 * @param keyValue
	 * @return boolean
	 */
	public boolean delete(String table, String key, String keyValue){
		Statement stmt = null ;
		String sql = "delete from " + table + " where " + key + "='" + keyValue + "';" ;
		System.out.println(sql);
		try{
			stmt = this.connection.createStatement() ;
			stmt.executeUpdate(sql) ;
			return true ;
		}catch (Exception e) {
			System.out.println("   " + table + "      : " + e.getLocalizedMessage());
			connectionRollback(connection) ;
			return false ;
		}
	}
	
	/**
	 *                  Vector<Vector<Object>>     
	 * @param table
	 * @param key
	 * @param keyValue
	 * @return Vector<Vector<Object>>
	 */
	public Vector<Vector<Object>> selectVector(String table, String key, String keyValue){
		Statement stmt = null ;
		ResultSet rs = null ;
		
		Vector<Vector<Object>> value = new Vector<Vector<Object>>() ;
		
		String sql = "select * from " + table + " where " + key + "='" + keyValue + "';" ;
		System.out.println(sql);
		try{
			stmt = this.connection.createStatement() ;
			rs = stmt.executeQuery(sql) ;
			int columnCounts = getFieldsCounts(rs) ;
			while(rs.next()){
				Vector<Object> valueVector = new Vector<Object>() ;
				for(int i = 1; i <= columnCounts ; i++){
					valueVector.addElement(rs.getObject(i)) ;
				}
				value.addElement(valueVector) ;
			}
			return value ;
		}catch (Exception e) {
			System.out.println("   " + table + "      : " + e.getLocalizedMessage());
			return value ;
		}
	}
	
	/**
	 *     sql     Vector<Vector<Object>>   
	 * @param sql sql  
	 * @return Vector<Vector<Object>>
	 */
	public Vector<Vector<Object>> selectVector(String sql){
		Statement stmt = null ;
		ResultSet rs = null ;
		
		Vector<Vector<Object>> value = new Vector<Vector<Object>>() ;
		
		System.out.println(sql);
		try{
			stmt = this.connection.createStatement() ;
			rs = stmt.executeQuery(sql) ;
			int columnCounts = getFieldsCounts(rs) ;
			while(rs.next()){
				Vector<Object> valueVector = new Vector<Object>() ;
				for(int i = 1; i <= columnCounts ; i++){
					valueVector.addElement(rs.getObject(i)) ;
				}
				value.addElement(valueVector) ;
			}
			return value ;
		}catch (Exception e) {
			System.out.println("   sql      : " + e.getLocalizedMessage());
			return value ;
		}
	}
	
	/**
	 *                    Object[][]    
	 * @param table
	 * @param key
	 * @param keyValue
	 * @return Object[][]
	 */
	public Object[][] selectObject(String table, String key, String keyValue){
		Statement stmt = null ;
		ResultSet rs = null ;
		
		int columns = getFieldsCounts(table) ;
		int rows = getTableCount(table, key, keyValue) ;
		
		Object[][] tableObject = new Object[rows][columns] ;
		
		String sql = "select * from " + table + " where " + key + "='" + keyValue + "';" ;
		System.out.println(sql);
		try{
			stmt = this.connection.createStatement() ;
			rs = stmt.executeQuery(sql) ;
			int i = 0 ;
			while(rs.next()){
				for(int j = 0 ; j < columns ; j++){
					tableObject[i][j] = rs.getObject(j+1) ;
				}
				i++ ;
			}
			return tableObject ;
		}catch (Exception e) {
			System.out.println("   " + table + "      : " + e.getLocalizedMessage());
			return tableObject ;
		}
	}
	
	/**
	 *            Vector<Vector<Object>>     
	 * @param table
	 * @param key
	 * @param keyValue
	 * @return Vector<Vector<Object>>
	 */
	public Vector<Vector<Object>> select(String table){
		Statement stmt = null ;
		ResultSet rs = null ;
		
		Vector<Vector<Object>> value = new Vector<Vector<Object>>() ;
		
		String sql = "select * from " + table + ";" ;
		System.out.println(sql);
		try{
			stmt = this.connection.createStatement() ;
			rs = stmt.executeQuery(sql) ;
			int columnCounts = getFieldsCounts(rs) ;
			while(rs.next()){
				Vector<Object> valueVector = new Vector<Object>() ;
				for(int i = 1; i <= columnCounts ; i++){
					valueVector.addElement(rs.getObject(i)) ;
				}
				value.addElement(valueVector) ;
			}
			return value ;
		}catch (Exception e) {
			System.out.println("   " + table + "      : " + e.getLocalizedMessage());
			return value ;
		}
	}
	
	/**
	 *            Object[][]     
	 * @param table
	 * @return Object[][]
	 */
	public Object[][] selectObject(String table){
		Statement stmt = null ;
		ResultSet rs = null ;
		
		int columns = getFieldsCounts(table) ;
		int rows = getTableCount(table) ;
		
		Object[][] tableObject = new Object[rows][columns] ;
		
		String sql = "select * from " + table + ";" ;
		System.out.println(sql);
		try{
			stmt = this.connection.createStatement() ;
			rs = stmt.executeQuery(sql) ;
			int i = 0 ;
			while(rs.next()){
				for(int j = 0 ; j < columns ; j++){
					tableObject[i][j] = rs.getObject(j+1) ;
				}
				i++ ;
			}
			return tableObject ;
		}catch (Exception e) {
			System.out.println("   " + table + "      : " + e.getLocalizedMessage());
			return tableObject ;
		}
	}
	
	/**
	 *    ResultSet          List    
	 * @param resultSet
	 * @return List<String>
	 */
	public List<String> getFields(ResultSet resultSet){
		List<String> fieldsList = new ArrayList<String>() ;
		try {
			int columnCounts = resultSet.getMetaData().getColumnCount();
			for(int i = 1 ; i <= columnCounts ; i++){
				fieldsList.add(resultSet.getMetaData().getColumnName(i)) ;
			}
		} catch (SQLException e) {
			System.out.println("         :" + e.getLocalizedMessage());
			return null ;
		}
		return fieldsList ;
	}
	
	/**
	 *            List    
	 * @param resultSet
	 * @return List<String>
	 */
	public List<String> getFields(String table){
		List<String> fieldsList = new ArrayList<String>() ;
		Statement stmt = null ;
		ResultSet rs = null ;
		String sql = "select * from " + table + ";" ;
		System.out.println(sql);
		try{
			stmt = this.connection.createStatement() ;
			rs = stmt.executeQuery(sql) ;
			fieldsList = getFields(rs) ;
		}catch (Exception e) {
			System.out.println("   " + table + "      : " + e.getLocalizedMessage());
		}
		return fieldsList ;
	}
	
	/**
	 *    ResultSet              
	 * @param resultSet
	 * @return int
	 */ 
	public int getFieldsCounts(ResultSet resultSet){
		try {
			return resultSet.getMetaData().getColumnCount();
		} catch (SQLException e) {
			System.out.println("         :" + e.getLocalizedMessage());
			return 0;
		}
	}
	
	/**
	 *             
	 * @param table
	 * @return int
	 */
	public int getFieldsCounts(String table){
		int counts = 0 ;
		Statement stmt = null ;
		ResultSet rs = null ;
		String sql = "select * from " + table + ";" ;
		System.out.println(sql);
		try{
			stmt = this.connection.createStatement() ;
			rs = stmt.executeQuery(sql) ;
			counts = getFieldsCounts(rs) ;
		}catch (Exception e) {
			System.out.println("   " + table + "      : " + e.getLocalizedMessage());
		}
		return counts ;
	}
	
	/**
	 *              
	 * @param table
	 * @return int
	 */
	private int getTableCount(String table){
		String sql = "select count(*) from " + table + ";" ;
		Statement stmt = null ;
		ResultSet rs = null ;
		int counts = 0 ;
		try {
			stmt = this.connection.createStatement() ;
			rs = stmt.executeQuery(sql) ;
			while(rs.next()){
				counts = rs.getInt(1) ;
			}
			return counts ;
		} catch (Exception e) {
			System.out.println("   " + table + "       : " + e.getLocalizedMessage());
			return counts ;
		}
	}
	
	/**
	 *                     
	 * @param table   
	 * @param key     
	 * @param keyValue    
	 * @return int
	 */
	private int getTableCount(String table, String key, String keyValue){
		String sql = "select count(*) from " + table + " where " + key + "='" + keyValue + "';";
		Statement stmt = null ;
		ResultSet rs = null ;
		int counts = 0 ;
		try {
			stmt = this.connection.createStatement() ;
			rs = stmt.executeQuery(sql) ;
			while(rs.next()){
				counts = rs.getInt(1) ;
			}
			return counts ;
		} catch (Exception e) {
			System.out.println("   " + table + "       : " + e.getLocalizedMessage());
			return counts ;
		}
	}
	
	private void connectionRollback(Connection connection){
		try {
			connection.rollback() ;
		} catch (SQLException e) {
			System.out.println("        : " + e.getLocalizedMessage()) ;
		}
	}
}


좋은 웹페이지 즐겨찾기