当前位置:网站首页>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;
}
边栏推荐
- Domain Driven Design and coding
- What are the advantages of VR panoramic production? Why is it favored?
- One way 和two way ANOVA分析的区别是啥,以及如何使用SPSS或者prism进行统计分析
- Overview of medium and low speed aerospace electronic bus
- Why are life science enterprises on the cloud in succession?
- ArcGIS loads free online historical images as the base map (no plug-ins are required)
- UE4 WebBrowser chart cannot display problems
- Adding, deleting, modifying and checking in low build code
- Difficult and miscellaneous problems: A Study on the phenomenon of text fuzziness caused by transform
- 水库大坝安全监测
猜你喜欢

离散数学及其应用 2018-2019学年春夏学期期末考试 习题详解

The new employee of the Department after 00 is really a champion. He has worked for less than two years. The starting salary of 18K is close to me when he changes to our company
Fuxin Kunpeng joins in, and dragon lizard community welcomes a new partner in format document technical service

MySQL log management

Svg line animation background JS effect

Reservoir dam safety monitoring

After 5 years of software testing in didi and ByteDance, it's too real

Interesting checkbox counters

部门新来的00后真是卷王,工作没两年,跳槽到我们公司起薪18K都快接近我了
More pictures | explain the Nacos parameters in detail!
随机推荐
Signal integrity (SI) power integrity (PI) learning notes (XXV) differential pair and differential impedance (V)
Sitelock helps you with the top ten common website security risks
Requests Library
Why are life science enterprises on the cloud in succession?
VIM use command
Fast pace? high pressure? VR panoramic Inn brings you a comfortable life
Report on operation mode and future development trend of global and Chinese propenyl isovalerate industry from 2022 to 2028
人体改造 VS 数字化身
Intensive reading of thinking about markdown
∞ symbol line animation canvasjs special effect
Analysis report on development mode and investment direction of sodium lauriminodipropionate in the world and China 2022 ~ 2028
Paper review: U2 net, u-net composed of u-net
Ten commandments of self-learning in machine learning
[Solved] Public key for mysql-community-xxx. rpm is not installed
MySQL日志管理
C program design topic 15-16 final exam exercise solutions (Part 1)
颜色渐变梯度颜色集合
Investment analysis and prospect forecast report of global and Chinese triglycine sulfate industry from 2022 to 2028
Technology sharing | wvp+zlmediakit realizes streaming playback of camera gb28181
C程序设计专题 18-19年期末考试习题解答(下)