当前位置:网站首页>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;
}
边栏推荐
- linux 系统redis常用命令
- Tape SVG animation JS effect
- In the past 5 years, from "Diandian" to the current test development, my success is worth learning from.
- Analysis report on development mode and investment direction of sodium lauriminodipropionate in the world and China 2022 ~ 2028
- Report on operation mode and future development trend of global and Chinese propenyl isovalerate industry from 2022 to 2028
- 【排行榜】Carla leaderboard 排行榜 运行与参与手把手教学
- Reservoir dam safety monitoring
- [leaderboard] Carla leaderboard leaderboard leaderboard operation and participation in hands-on teaching
- Eye gaze estimation using webcam
- [interview question] the difference between instancof and getclass()
猜你喜欢
Difficult and miscellaneous problems: A Study on the phenomenon of text fuzziness caused by transform
[leaderboard] Carla leaderboard leaderboard leaderboard operation and participation in hands-on teaching
Signal integrity (SI) power integrity (PI) learning notes (XXV) differential pair and differential impedance (V)
创意SVG环形时钟js特效
U.S. House of Representatives: digital dollar will support the U.S. dollar as the global reserve currency
Meta&伯克利基于池化自注意力机制提出通用多尺度视觉Transformer,在ImageNet分类准确率达88.8%!开源...
Difficult and miscellaneous problems: A Study on the phenomenon of text fuzziness caused by transform
无人驾驶: 对多传感器融合的一些思考
Discrete mathematics and its application detailed explanation of exercises in the final exam of spring and summer semester of 2018-2019 academic year
Collective例子
随机推荐
Requests Library
Difficult and miscellaneous problems: A Study on the phenomenon of text fuzziness caused by transform
[interview question] the difference between instancof and getclass()
C程序设计专题 18-19年期末考试习题解答(下)
【排行榜】Carla leaderboard 排行榜 运行与参与手把手教学
Creative SVG ring clock JS effect
UE4 WebBrowser图表不能显示问题
走近Harvest Moon:Moonbeam DeFi狂欢会
Hyperledger Fabric 2. X dynamic update smart contract
China CAE industry investment strategic planning and future development analysis report 2022 ~ 2028
Global and Chinese tetrahydrofurfuryl butyrate industry operation pattern and future prospect report 2022 ~ 2028
What is test development? Can you find a job at this stage?
5年,从“点点点”到现在的测试开发,我的成功值得每一个借鉴。
Ten commandments of self-learning in machine learning
Collection of software testing and game testing articles
Power application of 5g DTU wireless communication module
U.S. House of Representatives: digital dollar will support the U.S. dollar as the global reserve currency
Common redis commands in Linux system
How does VR panorama make money? Based on the objective analysis of the market from two aspects
干接点和湿接点