当前位置:网站首页>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;
}
边栏推荐
- D manual destruction may violate memory security
- Design and practice of vivo server monitoring architecture
- 使用网络摄像头进行眼睛注视估计
- After 5 years of software testing in didi and ByteDance, it's too real
- Approaching harvest moon:moonbeam DFI Carnival
- How to use promise Race() and promise any() ?
- How does VR panorama make money? Based on the objective analysis of the market from two aspects
- Related operations of ansible and Playbook
- 【排行榜】Carla leaderboard 排行榜 运行与参与手把手教学
- 【Proteus仿真】定时器0作为16位计数器使用示例
猜你喜欢

Why do more and more physical stores use VR panorama? What are the advantages?

水库大坝安全监测

∞ symbol line animation canvasjs special effect

∞符号线条动画canvasjs特效

第三代电力电子半导体:SiC MOSFET学习笔记(五)驱动电源调研

5年,从“点点点”到现在的测试开发,我的成功值得每一个借鉴。

Im instant messaging development application keeping alive process anti kill

Related operations of ansible and Playbook

有趣的checkbox计数器

JDBC —— 数据库连接
随机推荐
同济、阿里获CVPR最佳学生论文,李飞飞获黄煦涛奖,近6000人线下参会
Paper review: U2 net, u-net composed of u-net
离散数学及其应用 2018-2019学年春夏学期期末考试 习题详解
颜色渐变梯度颜色集合
Technology sharing | wvp+zlmediakit realizes streaming playback of camera gb28181
Outer screen and widescreen wasted? Harmonyos folding screen design specification teaches you to use it
干接点和湿接点
D does not require opapply() as a domain
水库大坝安全监测
Requests Library
教程详解|在酷雷曼系统中如何编辑设置导览功能?
技术分享| WVP+ZLMediaKit实现摄像头GB28181推流播放
MySQL semi sync replication
Eye gaze estimation using webcam
The third generation of power electronics semiconductors: SiC MOSFET learning notes (V) research on driving power supply
Domain Driven Design and coding
JPA learning 1 - overview, JPA, JPA core annotations, JPA core objects
Ott marketing is booming. How should businesses invest?
After 5 years of software testing in didi and ByteDance, it's too real
∞符号线条动画canvasjs特效