1,建立資料庫:繼承sqliteopenhelper
public class databasehelper extends sqliteopenhelper
@override
public void oncreate(sqlitedatabase db) catch (exception e)
} @override
public void onupgrade(sqlitedatabase db, int oldversion, int newversion)
}
這一句是建立資料庫,devicesoperation_tb:表名;後面都是欄位名,每一句以「,」逗號結束,最後一句不用db.execsql("create table devicesoperation_tb ("
+ "directory varchar (50) not null,"
+ "rootdir varchar (20) not null,"
+ "parentdir varchar (20) not null,"
+ "filename varchar (50) not null,"
+ "time varchar (50) not null"
+ ");");
2,獲取執行建立資料庫,得到資料庫:
只new是得不到資料庫的,必須要getreadabledatabase()或者getwriteabledatabase()一下才能看到資料庫,這句執行後,就可以在data/data/你的專案包名/databases下面看到有乙個devicesoperation_tb.db的資料庫了mdatabasehelper = new databasehelper(mcontext, database_name, null, 1);
msqlitedatabase = mdatabasehelper.getreadabledatabase();
3,資料庫新增資料,也就是insert語句:
說明:contentvalues :作用和amp差不多,放鍵值對的,當然key值要和你資料庫裡面的字段對應,要不然就報錯了msqlitedatabase.insert(devicesfiletb.devicesfile_tb, null, cv);要插入的表名,後面是cv,插入成功返回行號,失敗返回-1contentvalues cv = new contentvalues();
cv.put(devicesoperationtb.directory, f.tostring());
cv.put(devicesoperationtb.rootdir, filepath.split("/")[0]);
cv.put(devicesoperationtb.parentdir, filepath.split("/")[1]);
cv.put(devicesoperationtb.filename, filepath.split("/")[2]);
msqlitedatabase.insert(devicesfiletb.devicesfile_tb, null, cv);
4,資料庫查詢,query語句:
cursor mcursor = msqlitedatabase.query(devicesoperationtb.devicesoperation_tb, null, "directory = ?", new string , null, null, null);
引數1:表名
引數2:查詢到後返回這條資料那一列的值,如果null則返回整條資料的值
引數3:要查詢的列的字段
引數4:要查詢的值,引數3和引數4是對應的,如果查詢的是二列,後面的引數4也就2個值,
例:引數3是"directory = ? and filename = ?" 那麼引數4就應該是new string
注意:引數3裡面是二哥條件的話要用and而不是&
5,遍歷:
你查詢到結果,你要遍歷
cursor mcursor = msqlitedatabase.query(devicesoperationtb.devicesoperation_tb, null, "directory = ?", new string , null, null, null);
//先查詢,在遍歷
if (mcursor != null)
} }
6,刪除:delete語句
引數1:表名string whereargs = ;
msqlitedatabase.delete(tb, "filename=? and operation=?", whereargs);
引數2:條件,二個條件用and 我這句意思是:刪除filename = "測試.txt"並且operation="add"的那條資料
7,清空表,也是delete語句,引數不同而已:
msqlitedatabase.delete(tb, null, null);
無條件刪除,就是清空了
總結先到這裡吧,自己做筆記用,資料庫小白!
安卓SQLiteDatabase資料庫的使用
1.建立mydbopenhelper繼承自sqliteopenhelper用來管理資料庫 public class mydbopenhelper extends sqliteopenhelper 資料庫第一次建立時被呼叫 在資料庫第一次建立時,新增已知需要建立的固定 override public ...
安卓建立SQLite資料庫
新建乙個myopenhelper類,繼承sqliteopenhelper,實現它的構造方法和oncreate,onupgrade方法,構造方法myopenhelper有四個引數 1 context 上下文環境 2 name 資料庫的名字 3 factory 目的建立cursor 物件 4 versi...
安卓 Kotlin資料庫框架GreenDao的使用
優勢 1.訪問速度快 2.支援資料庫加密 3.輕量級 4.啟用實體 5.支援快取 6.自動生成 匯入依賴 專案中 buildscript dependencies implementation org.greenrobot greendao 3.2.2 add librarygreendao 首先建...