Android-SQLite (add, delete, modify, query) operation instance code

Source: Internet
Author: User

Five classes are required:

1. entity class: Person. java

2. abstract class: SQLOperate. java (encapsulates Database Operations)

3. helper class: DBOpenHelper. java (inherits SQLiteOpenHelper)

4. Implementation class: SQLOperateImpl. java (implement abstract class SQLOperate. java)

5. Test class: Test. java (inheriting AndroidTestCase)

1. Person. java

Copy codeThe Code is as follows: package com. mrzhu. sqltite;

Public class Person {

Private int _ id;
Private String name;

Public int getId (){
Return _ id;
}

Public void setId (int _ id ){
This. _ id = _ id;
}

Public String getName (){
Return name;
}

Public void setName (String name ){
This. name = name;
}

@ Override
Public String toString (){
Return "Person [id =" + _ id + ", name =" + name + "]";
}

Public Person (){
Super ();
}

Public Person (int _ id, String name ){
Super ();
This. _ id = _ id;
This. name = name;
}
}

2. SQLOperate. java

Copy codeThe Code is as follows: package com. mrzhu. sqltite;

Import java. util. List;

/**
* Add, delete, modify, and query
* @ Author ZLQ
*
*/
Public interface SQLOperate {
Public void add (Person p );
Public void delete (int id );
Public void updata (Person p );
Public List <Person> find ();
Public Person findById (int id );
}

3. DBOpenHelper. java

Copy codeThe Code is as follows: package com. mrzhu. sqltite;

Import android. content. Context;
Import android. database. sqlite. SQLiteDatabase;
Import android. database. sqlite. SQLiteOpenHelper;

/**
* Helper class
* @ Author ZLQ
*
*/
Public class DBOpneHelper extends SQLiteOpenHelper {

Private static final int VERSION = 1; // VERSION
Private static final String DB_NAME = "people. db"; // Database Name
Public static final String STUDENT_TABLE = "student"; // table name
Public static final String _ ID = "_ id"; // name of the column in the table
Public static final String NAME = "name"; // NAME of the column in the table
// Create a database statement, and add spaces before and after STUDENT_TABLE, _ ID, and NAME.
Private static final String CREATE_TABLE = "create table" + STUDENT_TABLE + "(" + _ ID + "Integer primary key autoincrement," + NAME + "text )";

Public DBOpneHelper (Context context ){
Super (context, DB_NAME, null, VERSION );
}

// Called when the database is created for the first time
@ Override
Public void onCreate (SQLiteDatabase db ){
Db.exe cSQL (CREATE_TABLE );
}

// Called during Version Upgrade
@ Override
Public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion ){

}

}

4. SQLOperateImpl. java

Copy codeThe Code is as follows: package com. mrzhu. sqltite;

Import java. util. ArrayList;
Import java. util. List;

Import android. content. ContentValues;
Import android. content. Context;
Import android. database. Cursor;
Import android. database. sqlite. SQLiteDatabase;

Public class SQLOperateImpl implements SQLOperate {

Private DBOpneHelper dbOpenHelper;

Public SQLOperateImpl (Context context ){
DbOpenHelper = new DBOpneHelper (context );
}

/**
* Add: Use insert to insert data to the database.
*/
Public void add (Person p ){
SQLiteDatabase db = dbOpenHelper. getWritableDatabase ();
ContentValues values = new ContentValues ();
Values. put (DBOpneHelper. _ ID, p. getId ());
Values. put (DBOpneHelper. NAME, p. getName ());
Db. insert (DBOpneHelper. STUDENT_TABLE, null, values );
}

/**
* Delete: delete data by id
*/
Public void delete (int id ){
SQLiteDatabase db = dbOpenHelper. getWritableDatabase ();
Db. delete (DBOpneHelper. STUDENT_TABLE, DBOpneHelper. _ ID + "=? ", New String [] {String. valueOf (id )});
}

/**
* Modify the data of the specified id.
*/
Public void updata (Person p ){
SQLiteDatabase db = dbOpenHelper. getWritableDatabase ();
ContentValues values = new ContentValues ();
Values. put (DBOpneHelper. _ ID, p. getId ());
Values. put (DBOpneHelper. NAME, p. getName ());
Db. update (DBOpneHelper. STUDENT_TABLE, values, DBOpneHelper. _ ID + "=? ", New String [] {String. valueOf (p. getId ())});
}

/**
* Query and query all the data in the table
*/
Public List <Person> find (){
List <Person> persons = null;
SQLiteDatabase db = dbOpenHelper. getReadableDatabase ();
Cursor cursor = db. query (DBOpneHelper. STUDENT_TABLE, null );
If (cursor! = Null ){
Persons = new ArrayList <Person> ();
While (cursor. moveToNext ()){
Person person = new Person ();
Int _ id = cursor. getInt (cursor. getColumnIndex (DBOpneHelper. _ ID ));
String name = cursor. getString (cursor. getColumnIndex (DBOpneHelper. NAME ));
Person. setId (_ id );
Person. setName (name );
Persons. add (person );
}
}
Return persons;
}

/**
* Query data of a specified id
*/
Public Person findById (int id ){
SQLiteDatabase db = dbOpenHelper. getReadableDatabase ();
Cursor cursor = db. query (DBOpneHelper. STUDENT_TABLE, null, DBOpneHelper. _ ID + "=? ", New String [] {String. valueOf (id)}, null );
Person person = null;
If (cursor! = Null & cursor. moveToFirst ()){
Person = new Person ();
Int _ id = cursor. getInt (cursor. getColumnIndex (DBOpneHelper. _ ID ));
String name = cursor. getString (cursor. getColumnIndex (DBOpneHelper. NAME ));
Person. setId (_ id );
Person. setName (name );
}
Return person;
}
}

5. Test. java

Add <application> </application> In AndroidManifest. xml

(TargetPackage is the package name of the current project)

<Instrumentation

Android: targetPackage = "com. mrzhu. sqltite"

Android: name = "android. test. InstrumentationTestRunner">

</Instrumentation>

In <application> </application>, add <uses-library android: name = "android. test. runner"/>

Copy codeThe Code is as follows: package com. mrzhu. sqltite;

Import java. util. List;

Import android. test. AndroidTestCase;
Import android. util. Log;

Public class Test extends AndroidTestCase {
Public void testAdd () throws Exception {
SQLOperateImpl test = new SQLOperateImpl (getContext ());
Person person = new Person (2, "Peter ");
Test. add (person );
}

Public void testDelete () throws Exception {
SQLOperateImpl test = new SQLOperateImpl (getContext ());
Test. delete (1 );
}

Public void testUpdata () throws Exception {
SQLOperateImpl test = new SQLOperateImpl (getContext ());
Person person = new Person (1, "Tom ");
Test. updata (person );
}

Public void testFind () throws Exception {
SQLOperateImpl test = new SQLOperateImpl (getContext ());
List <Person> persons = test. find ();
For (Person person: persons ){
Log. I ("System. out", person. toString ());
}
}

Public void testFindById () throws Exception {
SQLOperateImpl test = new SQLOperateImpl (getContext ());
Person person = test. findById (2 );
Log. I ("System. out", person. toString ());
}
}

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.