当前位置:网站首页>Android SQLite database

Android SQLite database

2022-06-25 00:19:00 Dream_ xang

Android-Sqlite database

This article USES the Sqlite database , The main use of DatabaseHelper Create a database table file , Use DBManger Operate on data .

1.DatabaseHelper initialization

The initialization part is placed in the Application To realize . Create a static variable

/**  database Helper object * */
public static DatabaseHelper databaseHelper = null;

 

stay OnCreate() Method .

//  Create database 
if (databaseHelper == null) {
   databaseHelper = DatabaseHelper.getDBHelper(context);
}

2.DatabaseHelper Implementation class


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * @author M.xang
 * @ Time  2018 year 11 month 8 Japan 
 * @ describe   database 
 */
public class DatabaseHelper extends SQLiteOpenHelper {

	SQLiteDatabase database;
	private static volatile DatabaseHelper instance = null;
	private static String DB_NAME = "name.db";//  Database name 
	private static int VERSION_NUM = 1;//  Database version 

	/**
	 * @param context  Context 
	 * @param name     Database name 
	 * @param factory  In order to create cursor object ,  The default is empty. 
	 * @param version  Database version 
	 */
	private DatabaseHelper(Context context, String name, CursorFactory factory, int version) {
		super(context, name, factory, version);
		database = this.getWritableDatabase();//  The database is not really created until this method is called 
	}

	/**
	 *  Create examples 
	 *
	 * @param context
	 * @return
	 */
	public static DatabaseHelper getDBHelper(Context context) {
		if (instance == null) {
			synchronized (DatabaseHelper.class) {
				if (instance == null) {
					instance = new DatabaseHelper(context,DB_NAME,null,VERSION_NUM);
				}
			}
		}
		return instance;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(DBManager.getInstance().createEXCSQL);
		db.execSQL(DBManager.getInstance().createOrderSQL);
	}

	/**
	 *  Database upgrade 
	 */
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		if (oldVersion < newVersion) {
			Log.e(" Database upgrade ", "oldVersion < newVersion " + oldVersion + "<" + newVersion);
		}
	}

}

3.DBManager Public class implementation

package com.wonder.collectionsystem.db;

import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicInteger;

import com.wonder.collectionsystem.MyApplication;
import com.wonder.collectionsystem.bean.ExcDBBean;
import com.wonder.collectionsystem.bean.OrderInfoBean;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

/**
 * @author M.xang
 * @ Time  2018 year 11 month 8 Japan 
 * @ describe   Database operation class 
 */
public class DBManager2 {

	private static DBManager2 dbManager;
	private AtomicInteger mOpenCounter = new AtomicInteger();
	private SQLiteDatabase mDatabase;

	public DBManager2() {
		super();
	}

	/**  get DBManger Instantiation  */
	public static final DBManager2 getInstance() {
		if (dbManager == null) {
			synchronized (DBManager2.class) {
				if (dbManager == null) {
					dbManager = new DBManager2();
				}
			}
		}
		return dbManager;
	}

	/**
	 *  Make sure you get the same instance , In this way, if the database read and write operations are placed in the thread , There will be no cursor closing problem 
	 * 
	 * @return
	 */
	private synchronized SQLiteDatabase getReadableDatabase() {
		if (mOpenCounter.incrementAndGet() == 1) {
			mDatabase = MyApplication.databaseHelper.getReadableDatabase();
		}
		return mDatabase;
	}

//----------------------------------------- Exception library table ------------------------------------------------
	/** TODO  Work order information - Table name  */
	private String TABLE_EXC = "ExcTable";
	/**  Delete import data table SQL sentence  */
	public final String dropSQL_EXC = "delete from " + TABLE_EXC;
	/**  Create table SQL sentence  */
	public final String createEXCSQL = "create table if not exists " + TABLE_EXC + "("
			+ "id integer PRIMARY KEY" + //  Primary key number 
			",devType varchar" + //  Device type 
			",excType varchar" + //  Exception types 
			",excXianXiang     varchar" + //  Abnormal phenomenon 
			",excXXID varchar" + //  Abnormal phenomenon ID
			",excReason     varchar" + //  Abnormal reason 
			",excReasonID varchar" + //  Abnormal reason ID
			",excReasonTypeID varchar" + //  Abnormal cause grouping ID
			")";

	/**
	 **  insert data 
	 * 
	 * @param saveBean
	 */
	public void insertRecord_EXC(ExcDBBean excDBBean) {
		SQLiteDatabase database = null;
		try {
			database = getReadableDatabase();
			String insertIntoTestDataSQL = "insert into " + TABLE_EXC + "(" + "excType" + //  Exception types 
					",excXianXiang" + //  Abnormal phenomenon 
					",excXXID" + //  Abnormal phenomenon ID
					",excReason" + //  Abnormal reason 
					",excReasonID" + //  Abnormal reason ID
					",devType" + //  Device type 
					",excReasonTypeID" + //  Abnormal cause grouping ID
					")" + " values(?,?,?,?,?,?,?)";
			SQLiteStatement statement = database.compileStatement(insertIntoTestDataSQL);
			statement.bindString(1, excDBBean.getExcType());
			statement.bindString(2, excDBBean.getExcXianXiang());
			statement.bindString(3, excDBBean.getExcXXID());
			statement.bindString(4, excDBBean.getExcReason());
			statement.bindString(5, excDBBean.getExcReasonID());
			statement.bindString(6, excDBBean.getDevType());
			statement.bindString(7, excDBBean.getExcReasonTypeID());
			statement.execute();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(database);
		}
	}

	/**
	 **  According to the type of equipment 、 Exception types 、 Query collection   Abnormal reason 
	 * 
	 * @param devType  Device type 
	 * @param excType  Exception types 
	 * @return
	 */
	public ArrayList<ExcDBBean> queryCaiJiByDevAndExcType(String devType, String excType) {
		String sql = "select * from " + TABLE_EXC + " where devType='" + devType + "' and excType='" + excType
				+ "'";
		return query(sql);
	}

	/**
	 **  According to the type of equipment 、 Exception types 、 Abnormal phenomenon query abnormal data , And then according to the   Abnormal phenomenon ID  Query all abnormal causes 
	 * 
	 * @param devType       Device type 
	 * @param excType       Exception types 
	 * @param excXianXiang  Abnormal phenomenon 
	 * @return
	 */
	public ArrayList<ExcDBBean> queryByDevExcTypeAndExcXX(String devType, String excType,
			String excXianXiang) {
		ArrayList<ExcDBBean> arrayResult = new ArrayList<ExcDBBean>();
		String sql = "select * from " + TABLE_EXC + " where devType='" + devType + "' and excType='" + excType
				+ "' and excXianXiang='" + excXianXiang + "'";
		ArrayList<ExcDBBean> arrayList = query(sql);
		for (int i = 0; i < arrayList.size(); i++) {
			String excXXID = arrayList.get(i).getExcXXID();
			sql = "select * from " + TABLE_EXC + " where excXXID='" + excXXID + "'";
			ArrayList<ExcDBBean> arrayList2 = query(sql);
			for (int j = 0; j < arrayList2.size(); j++) {
				String excReasonTypeID = arrayList2.get(j).getExcReasonTypeID();
				sql = "select * from " + TABLE_EXC + " where excReasonTypeID='" + excReasonTypeID + "'";
				ArrayList<ExcDBBean> arrayList3 = query(sql);
				arrayResult.addAll(arrayList3);
			}
		}
		return arrayResult;
	}

	/**
	 *  Query all exception types 
	 * 
	 * @param devType
	 * @return
	 */
	public ArrayList<ExcDBBean> queryAllExcType(String excType) {
		String sql = "select * from " + TABLE_EXC + " where excType='" + excType + "'";
		return query(sql);
	}
	//  UPDATE statement 
	// String updateSQL = "update " + TABLE_ORDER + " set " + "state='" + state + "'
	// where orderNum='" + orderNum + "'";

	private ArrayList<ExcDBBean> query(String sql) {
		ArrayList<ExcDBBean> list = new ArrayList<ExcDBBean>();
		SQLiteDatabase database = getReadableDatabase();
		Cursor cursor = database.rawQuery(sql, null);
		int count = cursor.getCount();
		try {
			if (count > 0) {//  Records 
				int excTypeIndex = cursor.getColumnIndex("excType");
				int excXianXiangIndex = cursor.getColumnIndex("excXianXiang");
				int excXXIDIndex = cursor.getColumnIndex("excXXID");
				int excReasonIndex = cursor.getColumnIndex("excReason");
				int excReasonIDIndex = cursor.getColumnIndex("excReasonID");
				int devTypeIndex = cursor.getColumnIndex("devType");
				int excReasonTypeIDIndex = cursor.getColumnIndex("excReasonTypeID");

				for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
					String excType = getString(cursor, excTypeIndex);
					String excXianXiang = getString(cursor, excXianXiangIndex);
					String excXXID = getString(cursor, excXXIDIndex);
					String excReason = getString(cursor, excReasonIndex);
					String excReasonID = getString(cursor, excReasonIDIndex);
					String devType = getString(cursor, devTypeIndex);
					String excReasonTypeID = getString(cursor, excReasonTypeIDIndex);

					ExcDBBean excDBBean = new ExcDBBean();
					excDBBean.setExcType(excType);
					excDBBean.setExcXianXiang(excXianXiang);
					excDBBean.setExcXXID(excXXID);
					excDBBean.setExcReason(excReason);
					excDBBean.setExcReasonID(excReasonID);
					excDBBean.setDevType(devType);
					excDBBean.setExcReasonTypeID(excReasonTypeID);
					;
					list.add(excDBBean);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null) {
				cursor.close();
			}
			closeDB(database);
		}
		return list;
	}

	/**
	 **  Delete all tables in the database 
	 * 
	 * @return
	 */
	public boolean deleteEXCTable() {
		boolean Ret = false;
		SQLiteDatabase database = null;
		try {
			database = getReadableDatabase();
			database.beginTransaction();//  Start business 
			database.execSQL(dropSQL_EXC);//  Delete exception table 
			database.setTransactionSuccessful();//  Transaction completion 
			Ret = true;
			database.endTransaction();//  End the business 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(database);//  Release database resources 
		}
		return Ret;
	}

	/**
	 *  Close the database to release database resources 
	 */
	private void closeDB(SQLiteDatabase database) {
		try {
			if (database != null) {
				//  The current value of the field of the given object managed by the updater is “0” When , Just officially shut down the database 
				if (mOpenCounter.decrementAndGet() == 0) {
					database.close();//  Release database resources 
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 *  Delete all tables in the database 
	 * 
	 * @return
	 */
	public boolean deleteAllDBTable() {
		boolean Ret = false;
		SQLiteDatabase database = null;
		try {
			database = getReadableDatabase();
			database.beginTransaction();//  Start business 
//			database.execSQL(dropSQL_EXC);//  Delete exception Library 
			database.setTransactionSuccessful();//  Transaction completion 
			Ret = true;
			database.endTransaction();//  End the business 
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeDB(database);//  Release database resources 
		}
		return Ret;
	}

	private String getString(Cursor cursor, int index) {
		if (cursor != null && index >= 0) {
			return cursor.getString(index);
		}
		return "";
	}

	@SuppressWarnings("unused")
	private int getInt(Cursor cursor, int index) {
		if (cursor != null && index >= 0) {
			return cursor.getInt(index);
		}
		return 0;
	}

	@SuppressWarnings("unused")
	private int getLong(Cursor cursor, int index) {
		if (cursor != null && index >= 0) {
			return (int) cursor.getLong(index);
		}
		return 0;
	}

}

In obtaining SQLiteDatabase Of database Object time , Here we use getReadableDatabase() Method , This way of writing is to prevent reading and writing to the database in the thread , The data flow is closed .

private synchronized SQLiteDatabase getReadableDatabase() {
    if (mOpenCounter.incrementAndGet() == 1) {
        mDatabase = MyApplication.databaseHelper.getReadableDatabase();
    }
    return mDatabase;
}

 

 

 

 

 

原网站

版权声明
本文为[Dream_ xang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202210550591286.html