一、Sqlite數據庫介紹
二、Sqlite數據庫增刪改查在Android開發中應用
Sqlite數據庫數據常用類型介紹
1、每個存儲在 SQLite 數據庫中的值都具有以下存儲類之一:
NULL :值是一個 NULL 值。
INTEGER: 值是一個帶符號的整數,根據值的大小存儲在 1、2、3、4、6 或 8 字節中。
REAL : 值是一個浮點值,存儲爲 8 字節的 IEEE 浮點數字
TEXT:值是一個文本字符串,使用數據庫編碼(UTF-8、UTF-16BE 或 UTF-16LE)存儲
BLOB:值是一個 blob 數據,完全根據它的輸入存儲。
2、Sqlite親和類型
親和類型 | 描述 |
---|---|
TEXT | 數值型數據在被插入之前,需要先被轉換爲文本格式,之後再插入到目標字段中。 |
NUMERIC | 當文本數據被插入到親緣性爲NUMERIC的字段中時,如果轉換操作不會導致數據信息丟失以及完全可逆,那麼SQLite就會將該文本數據轉換爲INTEGER或REAL類型的數據,如果轉換失敗,SQLite仍會以TEXT方式存儲該數據。對於NULL或BLOB類型的新數據,SQLite將不做任何轉換,直接以NULL或BLOB的方式存儲該數據。需要額外說明的是,對於浮點格式的常量文本,如"30000.0",如果該值可以轉換爲INTEGER同時又不會丟失數值信息,那麼SQLite就會將其轉換爲INTEGER的存儲方式。 |
INTEGER | 對於親緣類型爲INTEGER的字段,其規則等同於NUMERIC,唯一差別是在執行CAST表達式時。 |
REAL | 其規則基本等同於NUMERIC,唯一的差別是不會將"30000.0"這樣的文本數據轉換爲INTEGER存儲方式。 |
NONE | 不做任何的轉換,直接以該數據所屬的數據類型進行存儲。 |
INTEGER : INT , INTEGER ,TINYINT , SMALLINT ,MEDIUMINT ,BIGINT ,UNSIGNED BIG INT ,INT2 ,INT8
TEXT: CHARACTER(20) 、VARCHAR(255)、VARYING CHARACTER(255)、NCHAR(55)、NATIVE CHARACTER(70)、NVARCHAR(100)、TEXT、CLOB
NONE:BLOB no datatype specified
REAL:REAL、DOUBLE、DOUBLE PRECISION、FLOAT
NUMERIC:NUMERIC、DECIMAL(10,5)、BOOLEAN、DATE、DATETIME
SQLite 沒有單獨的 Boolean 存儲類。相反,布爾值被存儲爲整數 0(false)和 1(true)。
Sqlite數據庫在Android應用中使用
Android 平臺內置了豐富的API可以供開發者調用SQLIte數據庫
1、首先繼承 SQLiteOpenHelper 類 並實現裏面的 onCreate(SQLiteDatabase db)方法和 onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
onCreate 方法是應用程創建數據庫及其表
onUpgrade 數據庫版更新調用
2、創建一個單例類 LeDBManager 管理數據的增刪改查
public class LeDBManager {
private static Context mContext;
private LeDBOpenHelper mDbOpenHelper;
private LeDBManager(Context context) {
mDbOpenHelper = new LeDBOpenHelper(context);
}
private static class SingletonHolder {
private static final LeDBManager INSTANCE = new LeDBManager(mContext);
}
public static final LeDBManager getInstance(Context context) {
mContext = context;
return SingletonHolder.INSTANCE;
}
//....................
}
代碼的具體實現如下:
LeDBOpenHelper 類實現
public class LeDBOpenHelper extends SQLiteOpenHelper {
private static final int DB_VERSION = 1 ; // 數據庫版本
private static final String DB_NAME = "leNet.db" ; // 數據庫名稱
public LeDBOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(createDownloadTable);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public static final String TABLE_DOWNLOAD = "table_download" ;
public static final String DOWNLOAD_NAME = "download_name" ;
public static final String DOWNLOAD_URL = "download_url" ;
public static final String DOWNLOAD_PATH = "download_path" ;
public static final String DOWNLOAD_TOTAL_SIZE = "download_total_size" ;
public static final String DOWNLOAD_DOWNLOAD_SIZE = "download_download_size" ;
public static final String DOWNLOAD_STATUS = "download_status" ;
private String createDownloadTable = "create table if not exists table_download (" +
"id integer primary key autoincrement," +
"download_name varchar ," +
"download_url varchar ," +
"download_path varchar ," +
"download_total_size long ," +
"download_download_size long," +
"download_status smallint" +
")" ;
}
LeDBManager 中實現數據的增刪改查
/**
* Created by familylove on 2017/4/26.
* 數據庫
* 增
* 刪
* 改
* 查
* 管理類
*/
public class LeDBManager {
private static Context mContext;
private LeDBOpenHelper mDbOpenHelper;
private LeDBManager(Context context) {
mDbOpenHelper = new LeDBOpenHelper(context);
}
private static class SingletonHolder {
private static final LeDBManager INSTANCE = new LeDBManager(mContext);
}
public static final LeDBManager getInstance(Context context) {
mContext = context;
return SingletonHolder.INSTANCE;
}
/**
* 插入數據
*
* @param bean
*/
public void insertDownload(DownloadBean bean) {
if (bean == null)
return;
SQLiteDatabase db = mDbOpenHelper.getWritableDatabase();
db.beginTransaction();
if (!isExistsDownload(db, bean.getUrl())) {
db.insert(LeDBOpenHelper.TABLE_DOWNLOAD, null, bean.toContentValues(bean));
}
db.setTransactionSuccessful();
db.endTransaction();
if (db != null)
db.close();
}
/**
* 刪除數據
* @param tag
*/
public boolean deleteDownload(String tag){
boolean flag = false ;
if (TextUtils.isEmpty(tag))
return flag;
SQLiteDatabase db = mDbOpenHelper.getWritableDatabase() ;
db.beginTransaction();
int deleteFlag = db.delete(LeDBOpenHelper.TABLE_DOWNLOAD,LeDBOpenHelper.DOWNLOAD_URL+" = ? ",new String[]{tag}) ;
db.setTransactionSuccessful();
db.endTransaction();
if (db!=null)
db.close();
if (deleteFlag==1)
flag = true ;
else if (deleteFlag==0)
flag = false ;
return flag ;
}
/**
* 更新數據
*
* @param tag
* @param totalSize
* @param downloadSize
* @param status
*/
public void updateDownload(String tag, long totalSize, long downloadSize, int status) {
SQLiteDatabase db = mDbOpenHelper.getWritableDatabase();
db.beginTransaction();
if (isExistsDownload(db, tag)) {
ContentValues updateCV = new ContentValues();
updateCV.put(LeDBOpenHelper.DOWNLOAD_TOTAL_SIZE, totalSize);
updateCV.put(LeDBOpenHelper.DOWNLOAD_DOWNLOAD_SIZE, downloadSize);
updateCV.put(LeDBOpenHelper.DOWNLOAD_STATUS, status);
db.update(LeDBOpenHelper.TABLE_DOWNLOAD, updateCV, LeDBOpenHelper.DOWNLOAD_URL + " = ?", new String[]{tag});
}
db.setTransactionSuccessful();
db.endTransaction();
if (db != null)
db.close();
db = null;
}
/**
* 判斷數據是否存在
* @param db
* @param tag
* @return
*/
private boolean isExistsDownload(SQLiteDatabase db, String tag) {
boolean flag = false;
String sql = "select * from " + LeDBOpenHelper.TABLE_DOWNLOAD + " where " + LeDBOpenHelper.DOWNLOAD_URL + " = ? ";
Cursor cursor = db.rawQuery(sql, new String[]{tag});
if (cursor != null && cursor.getCount() > 0) {
flag = true;
} else {
flag = false;
}
if (cursor != null)
cursor.close();
return flag;
}
/**
* 數據查詢
* @param tag
* @return
*/
public DownloadBean queryOneDownload(String tag) {
DownloadBean bean = null;
SQLiteDatabase db = mDbOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery(
"select * from " + LeDBOpenHelper.TABLE_DOWNLOAD + " where " + LeDBOpenHelper.DOWNLOAD_URL + " = ?",
new String[]{tag});
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToNext()) {
bean = cursorToDownloadBean(cursor);
}
}
if (cursor != null)
cursor.close();
if (db != null)
db.close();
return bean;
}
/**
* 計算表 tableName 數據總量
* @param tableName
* @return 數據表數據總條數
*/
public int countDownloadBeans(String tableName){
int count = 0 ;
SQLiteDatabase db = mDbOpenHelper.getReadableDatabase() ;
Cursor cursor = db.rawQuery("select count(*) from "+tableName,null) ;
if (cursor!=null && cursor.getCount()>0){
cursor.moveToFirst() ;
count = cursor.getInt(0) ;
}
return count ;
}
/**
* cursor to bean
* @param cursor
* @return
*/
private DownloadBean cursorToDownloadBean(Cursor cursor) {
DownloadBean bean = new DownloadBean();
bean.setStatus(cursor.getInt(cursor.getColumnIndex(LeDBOpenHelper.DOWNLOAD_STATUS)));
bean.setDownloadSize(cursor.getLong(cursor.getColumnIndex(LeDBOpenHelper.DOWNLOAD_DOWNLOAD_SIZE)));
bean.setTotalSize(cursor.getLong(cursor.getColumnIndex(LeDBOpenHelper.DOWNLOAD_TOTAL_SIZE)));
bean.setUrl(cursor.getString(cursor.getColumnIndex(LeDBOpenHelper.DOWNLOAD_URL)));
bean.setName(cursor.getString(cursor.getColumnIndex(LeDBOpenHelper.DOWNLOAD_NAME)));
bean.setPath(cursor.getString(cursor.getColumnIndex(LeDBOpenHelper.DOWNLOAD_PATH)));
return bean;
}
}
DownloadBean類
public class DownloadBean implements Serializable {
private String name;
private String path;
private String url;
private int status = 0;
private long totalSize;
private long downloadSize;
public long getDownloadSize() {
return downloadSize;
}
public void setDownloadSize(long downloadSize) {
this.downloadSize = downloadSize;
}
public long getTotalSize() {
return totalSize;
}
public void setTotalSize(long totalSize) {
this.totalSize = totalSize;
}
public DownloadBean() {
}
public DownloadBean(String name, String path, String url) {
this.name = name;
this.path = path;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
@Override
public String toString() {
return "DownloadBean{" +
"name='" + name + '\'' +
", path='" + path + '\'' +
", url='" + url + '\'' +
", status=" + status +
", totalSize=" + totalSize +
", downloadSize=" + downloadSize +
'}';
}
public ContentValues toContentValues(DownloadBean bean) {
ContentValues cv = new ContentValues();
cv.put(LeDBOpenHelper.DOWNLOAD_STATUS, bean.getStatus());
cv.put(LeDBOpenHelper.DOWNLOAD_DOWNLOAD_SIZE, bean.getDownloadSize());
cv.put(LeDBOpenHelper.DOWNLOAD_TOTAL_SIZE, bean.getTotalSize());
cv.put(LeDBOpenHelper.DOWNLOAD_PATH, bean.getPath());
cv.put(LeDBOpenHelper.DOWNLOAD_URL, bean.getUrl());
cv.put(LeDBOpenHelper.DOWNLOAD_NAME, bean.getName());
return cv;
}
}