当前位置:网站首页>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;
}
边栏推荐
- 【排行榜】Carla leaderboard 排行榜 运行与参与手把手教学
- Analysis report on operation pattern and supply and demand situation of global and Chinese cyano ketoprofen industry from 2022 to 2028
- Tongji and Ali won the CVPR best student thesis, lifeifei won the Huang xutao award, and nearly 6000 people attended the offline conference
- 在滴滴和字节跳动干了 5年软件测试,太真实…
- D manual destruction may violate memory security
- One way 和two way ANOVA分析的区别是啥,以及如何使用SPSS或者prism进行统计分析
- [figure database performance and scenario test sharp tool ldbc SNB] series I: introduction to data generator & Application to ges service
- Why do more and more physical stores use VR panorama? What are the advantages?
- Signal integrity (SI) power integrity (PI) learning notes (I) introduction to signal integrity analysis
- canvas线条的动态效果
猜你喜欢

Wx applet jump page

创意SVG环形时钟js特效

wx小程序跳转页面

What is the difference between one way and two way ANOVA analysis, and how to use SPSS or prism for statistical analysis

技术分享| WVP+ZLMediaKit实现摄像头GB28181推流播放

Difficult and miscellaneous problems: A Study on the phenomenon of text fuzziness caused by transform

为什么越来越多的实体商铺用VR全景?优势有哪些?

Technology sharing | wvp+zlmediakit realizes streaming playback of camera gb28181

Do280openshift access control -- encryption and configmap
How can I persuade leaders to use DDD to construct the liver project?
随机推荐
Analysis report on operation mode and future development of global and Chinese methyl cyclopentanoate industry from 2022 to 2028
Report on operation mode and future development trend of global and Chinese propenyl isovalerate industry from 2022 to 2028
[issue 25] face to face experience of golang Engineer in the rightmost social recruitment
MySQL log management
无需显示屏的VNC Viewer远程连接树莓派
WordPress add photo album function [advanced custom fields Pro custom fields plug-in series tutorial]
How to delete the entire row with duplicate items in a column of WPS table
C program design topic 18-19 final exam exercise solutions (Part 2)
Difficult and miscellaneous problems: A Study on the phenomenon of text fuzziness caused by transform
Why do more and more physical stores use VR panorama? What are the advantages?
第三代电力电子半导体:SiC MOSFET学习笔记(五)驱动电源调研
Tutorial details | how to edit and set the navigation function in the coolman system?
Why are life science enterprises on the cloud in succession?
Difficult and miscellaneous problems: A Study on the phenomenon of text fuzziness caused by transform
D does not require opapply() as a domain
VR全景制作的优势是什么?为什么能得到青睐?
What is test development? Can you find a job at this stage?
Color gradient gradient color collection
[figure database performance and scenario test sharp tool ldbc SNB] series I: introduction to data generator & Application to ges service
Microsoft won the title of "leader" in the magic quadrant of Gartner industrial Internet of things platform again!