Using SQLite in Android to make additions and deletions to data

Source: Internet
Author: User

Stop a day, I ' m back again~~ when we need to manipulate a lot of data, the first thing we think of is the database, because you can use simple statements to implement the data deletion and modification, in Android, we do not use SQL or Oracle, we are using SQLite, Because it consumes less resources, the statement format is the same as the SQL statement.

First of all, we have to implement the database creation and pruning in Android, referencing the database class, no longer inherit the common activity class, but inherit the Sqliteopenhelper in Android, create a construction method, four parameters are (Context Context, String name, sqlitedatabase.cursorfactory factory,int version), let's explain each of these four parameters separately, the context represents the contextual environment, Most of the situation is that the context is Activity,name is the name of the database, usually we write "xxx.db", so it is convenient to know that we create a database, the cursor represents a pointer, when the default is null, it represents the initial 1, and then point to each row of the database, We can use the cursor to scan the database, the conditional scan is the lookup, version represents the revision number, as long as the setting of a value greater than or equal to 1. In the database class must call two methods, namely OnCreate () and OnUpdate () method, passed in parameters are database objects, which are called when the database is created and the database is updated, create the table when the database is created, directly call the Execute Database statement method Execsql ( String) with the following code:

 PackageCom.administrator.sqlite;ImportAndroid.content.Context;Importandroid.database.sqlite.SQLiteDatabase;ImportAndroid.database.sqlite.SQLiteOpenHelper;Importandroid.provider.Settings;/*** Created by Administrator on 2016/7/22.*/ Public classMyopenhelperextendsSqliteopenhelper {//The constructor method, which is called when new, cursor: Encapsulates the data returned by the database query, initially 1. Reads the next row of data down, and NULL uses the default cursor     PublicMyopenhelper (context context, String name, Sqlitedatabase.cursorfactory factory,intversion) {        Super(context,name,factory,version); }    //when the database is created, this method invokes the//Create a table while creating a database@Override Public voidonCreate (Sqlitedatabase db) {String SQL= "CREATE table student (number char (4) Primary Key,name char (4), age char (1))";    Db.execsql (SQL); }   //when the database is upgraded, this method invokes the@Override Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) {System.out.println ("The database has been upgraded"); }}

Below we use unit test method to realize the database of adding and deleting, write in Applicationtest, first we define a Myopenhelper object, at this time we are testing, there is no foreground task, so there is no activity that is executing at this time, Android provides us with the GetContext () method, which is used to create a virtual context for us in the absence of context. Next we call Getreadabledatabase () to create or open a database (if not, we create a database, if so, we open the database), the data additions and deletions to the operation, is to create the good one database and execute the corresponding SQL statement, Finally, close the database. The code is as follows:

 PackageCom.administrator.sqlite;Importandroid.app.Application;ImportAndroid.database.Cursor;Importandroid.database.sqlite.SQLiteDatabase;Importandroid.test.ApplicationTestCase;/*** <a href= "http://d.android.com/tools/testing/testing_android.html">testing fundamentals</a>*/ Public classApplicationtestextendsApplicationtestcase<application> {     Publicapplicationtest () {Super(Application.class); }     Public voidTestinsert () {myopenhelper moh=NewMyopenhelper (GetContext (), "student.db",NULL, 2); Sqlitedatabase DB=moh.getreadabledatabase (); Db.execsql (INSERT into student values (?,?,?),Newobject[]{"1234", "Lily", "19"}); Db.execsql (INSERT into student values (?,?,?),Newobject[]{"1235", "Bob", "20"}); Db.execsql (INSERT into student values (?,?,?),Newobject[]{"1236", "Amy", "18"}); Db.execsql (INSERT into student values (?,?,?),Newobject[]{"1237", "Tom", "21"}); Db.execsql (INSERT into student values (?,?,?),Newobject[]{"1238", "Alice", "18"}); Db.execsql (INSERT into student values (?,?,?),Newobject[]{"1239", "Grace", "20"}); Db.execsql (INSERT into student values (?,?,?),Newobject[]{"1240", "Henry", "23"}); Db.execsql (INSERT into student values (?,?,?),Newobject[]{"1241", "David", "40"}); Db.execsql (INSERT into student values (?,?,?),Newobject[]{"1242", "Soada", "17"});    Db.close (); }     Public voidTestdelete () {myopenhelper moh=NewMyopenhelper (GetContext (), "student.db",NULL, 2); Sqlitedatabase DB=moh.getreadabledatabase (); Db.execsql ("Delete from student where number=?",Newobject[]{1241});    Db.close (); }     Public voidtestupdate () {myopenhelper moh=NewMyopenhelper (GetContext (), "student.db",NULL, 2); Sqlitedatabase DB=moh.getreadabledatabase (); Db.execsql ("Update student set number=?" Where Name=? ",Newobject[]{"1314", "Soada"});    Db.close (); }}

For the lookup operation of the database, we need to use the cursor implementation to scan the database by row, and fetch the matching data, we call the Rawquery method, the first parameter is a SELECT statement, the second parameter is the value of the placeholder parameter in the SELECT statement, If the SELECT statement does not use a placeholder (that is, a where statement), the parameter can be set to null and a cursor is returned. The Scan method is: If the next row that the cursor points to is not empty, it gets the value of each property in each row, allowing multiple rows of scanning and obtaining data for the entire database. We also want to emphasize that the argument passed by the GetString () method is an integer index value that represents the index value of the property, the first is 0, and so on, but we do not know the exact value in the case of the database structure, so we usually call the Getcolumnindex method. The code is as follows:

1  Public voidTestselect () {2Myopenhelper moh=NewMyopenhelper (GetContext (), "student.db",NULL, 2);3Sqlitedatabase db=moh.getreadabledatabase ();4Cursor cursor=db.rawquery ("SELECT * FROM Student",NULL);5          while(Cursor.movetonext ()) {6             //get the next row of data7String number = cursor.getstring (Cursor.getcolumnindex ("number"));8String name = cursor.getstring (Cursor.getcolumnindex ("name"));9String age = cursor.getstring (Cursor.getcolumnindex ("Age"));TenSystem.out.println (number+ ";") +name+ ";" +Age ); One db.close (); A}

Let's examine each of them individually:

Add several data into the database student:

Delete a record: Delete a record with number 1241

Modify a record: Soada number changed to 1314

We have mastered the use of SQLite in Android to change the data additions and deletions, the next section we want to achieve is to display each record of the database to the screen in turn.

Using SQLite in Android to make additions and deletions to data

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.