Android SQLite Database

Source: Internet
Author: User
Tags sqlite database

OK, now let's take a look at some basic things about using SQLite database in Android.

对于大多数app而言对数据库的要求很简单,无非CURD,仅此而已。而我个人比较喜欢将所要使用的相应数据    表封装成javabean再进行操作,这样会显得逻辑比较清晰。

First, we write an entity:

Package wenyue.justdoit.entity; Public classTododata {PrivateString Todotadkname;Private intId Public int getId() {returnID;} Public void setId(intID) { This. id = ID;} Public Tododata() {} PublicStringGettodotadkname() {returnTodotadkname;} Public void Settodotadkname(String todotadkname) { This. Todotadkname = Todotadkname;}}

After that, we need a tool class that inherits the Sqliteopenhelper. After that, we only need to instantiate the entity when it is working on the database.

SQLiteOpenHelper需要重写onCreate,onUpgrade方法。android已经对sqlite数据库的操作进行了封装,所以若是你想要更深入了解数据库操作,可以参考JDBC的使用。OnCreate再首次创建数据库时调用。而我们要进行数据库操作时可用SQLiteDatabase db = this.getWritableDatabase()。文档说该方法使db获得了写数据库的权限,感觉其实就是拿到了相应数据库的廉洁实体。

Then the following directly affixed to inherit the Sqliteopenhelper tool class code bar, after all, are some very simple things, look at the method name can know what is doing.

 PackageWenyue.justdoit.util;ImportJava.util.ArrayList;ImportJava.util.List;ImportWenyue.justdoit.entity.todoData;ImportAndroid.content.ContentValues;ImportAndroid.content.Context;ImportAndroid.database.Cursor;ImportAndroid.database.sqlite.SQLiteDatabase;ImportAndroid.database.sqlite.SQLiteOpenHelper;ImportAndroid.util.Log; Public  class dbhelper extends sqliteopenhelper {Private Static Final intDatabase_version =1;//Database NamePrivate Static FinalString database_name ="Todolistmanager";//Tasks table namePrivate Static FinalString Table_tasks ="ToDoList";//Tasks Table Columns namesPrivate Static FinalString key_id ="id";Private Static FinalString Key_taskname ="Todotadkname"; Public DBHelper(Context context) {Super(Context, database_name,NULL, database_version);//TODO auto-generated constructor stub}@Override Public void onCreate(Sqlitedatabase db) {String sql ="CREATE TABLE IF not EXISTS"+ Table_tasks +" ( "+ key_id +"INTEGER PRIMARY KEY autoincrement,"+ Key_taskname +"TEXT"+")"; Db.execsql (SQL);//Db.close ();}@Override Public void Onupgrade(Sqlitedatabase DB,intOldversion,intNewVersion) {Db.execsql ("DROP TABLE IF EXISTS"+ table_tasks);//Create tables againOnCreate (db);} Public void Save(Tododata testdata) {Sqlitedatabase db = This. Getwritabledatabase (); Contentvalues values =NewContentvalues ();    Values.put (Key_taskname, Testdata.gettodotadkname ()); Db.insert (Table_tasks,NULL, values); Db.close ();} PublicList<tododata>Getalltasks() {list<tododata> taskList =NewArraylist<tododata> ();//Select all QueryString SelectQuery ="SELECT * from"+ table_tasks; Sqlitedatabase db = This. Getwritabledatabase (); cursor cursor = db.rawquery (SelectQuery,NULL);//Looping through all rows and adding to list    if(Cursor.movetofirst ()) {do {Tododata task =NewTododata (); Task.setid (Cursor.getint (0)); Task.settodotadkname (Cursor.getstring (1));//Adding contact to ListTasklist.add (Task); } while(Cursor.movetonext ()); } db.close ();returnTaskList;} Public int checkisexits(String s) {List<tododata> taskList =NewArraylist<tododata> (); String SelectQuery ="SELECT * from"+ Table_tasks +"WHERE"+ Key_taskname +" = ?"; Sqlitedatabase db = This. Getwritabledatabase (); cursor cursor = db.rawquery (SelectQuery,NewString[] {s});if(Cursor.movetofirst ()) {do {Tododata task =NewTododata (); Task.setid (Cursor.getint (0)); Task.settodotadkname (Cursor.getstring (1));//Adding contact to ListTasklist.add (Task); } while(Cursor.movetonext ()); } log.i ("Checkisexits", String.valueof (Tasklist.size ())); Db.close ();returnTasklist.size ();} Public int GetTaskID(String tsakname) {List<tododata> taskList =NewArraylist<tododata> (); String SelectQuery ="SELECT * from"+ Table_tasks +"WHERE"+ Key_taskname +" = ?"; Sqlitedatabase db = This. Getwritabledatabase (); cursor cursor = db.rawquery (SelectQuery,NewString[] {tsakname});if(Cursor.movetofirst ()) {do {Tododata task =NewTododata (); Task.setid (Cursor.getint (0)); Task.settodotadkname (Cursor.getstring (1));//Adding contact to ListTasklist.add (Task); } while(Cursor.movetonext ()); } log.i ("get_task_id", String.valueof (Tasklist.get (0). GetId ())); Db.close ();returnTasklist.get (0). GetId ();} Public void Updatetask(String TaskName,intID) {LOG.I ("Updatetask", string.valueof (ID) +"-------------"+ TaskName);//Updating rowSqlitedatabase db = This. Getwritabledatabase (); Contentvalues values =NewContentvalues ();    Values.put (Key_taskname, taskname);    string[] args = {string.valueof (id)}; Db.update (Table_tasks, values, key_id +" = ?", args); LOG.I ("Updatesuccess", string.valueof (ID)); Db.close ();} Public void Deletetask(String taskname) {Sqlitedatabase db = This. Getwritabledatabase ();    string[] args = {string.valueof (taskname)}; Db.delete (table_tasks, Key_taskname +"=?", args); Db.close ();}}

As for the specific data processing will not have to say, you get the instance, call the appropriate method. All right, so much for the first write.

Android SQLite Database

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.