Practical Android development-Database Operations

Source: Internet
Author: User
Tags name database

In our framework, there is a file called DBTool. java, which is obviously the class we use to process databases. In Android development, the database we operate on is a small SQLite database, a small mobile phone. Of course, it cannot be a big guy like MSSQL or MySQL. At the same time, high resource consumption is also an issue that must be paid attention to in mobile development. Therefore, a small and easy-to-use database has become our good partner!

 

 

 

First, report the progress of the current project. We have been developing the Model for several days, that is, requesting the interface to obtain data. Now most of them have been written, mainly because iphone outsourcing companies have not submitted them yet, so we can only develop at the lowest level first. After opening the Tools package, we will study the parsing of the Model layer and XML.

 

 

 

Let's take a look at the complete code and then describe it one by one.

 

 

 

 

 

 

Package hb. hbwb. tools;

 

Import hb. hbwb. finals. DBFinals;

Import android. content. ContentValues;

Import android. content. Context;

Import android. database. Cursor;

Import android. database. SQLException;

Import android. database. sqlite .*;

 

/**

* @ Name database operations

* @ Author zhang. yue

* @ Create_date 20110512

* @ Last_edit_author zhang. yue

* @ Last_edit_date 20111115

* @ Remark

* @ Edit_remark optimization code

*/

Public class DBTool {

Private Context mCtx = null;

Private DatabaseHelper dbHelper = null;

Private SQLiteDatabase db = null;

/**

* Constructor 1

* @ Param ctx context object

*/

Public DBTool (Context ctx ){

This. mCtx = ctx;

}

/**

* Open a data connection

* @ Return

* @ Throws SQLException

*/

Public DBTool open () throws SQLException {

DbHelper = new DatabaseHelper (mCtx );

Db = dbHelper. getWritableDatabase (); // if the database does not exist, create one. Otherwise, update the database based on the version.

Return this;

}

/**

* Close data connection

*/

Public void close (){

DbHelper. close ();

}

/**

* 1 is used for list query.

* @ Param tableName: Table Name

* @ Param strCols column name

* @ Param strWhere Condition

* @ Param strGroupby Group

* @ Param strOrderby sorting

* @ Return Data Pointer

*/

Public Cursor getAll (String tableName, String [] strCols, String strWhere, String strGroupby, String strOrderby ){

Return db. query (tableName, // table name

StrCols, // Column

StrWhere, // where statement

Null, // where statement Parameters

StrGroupby, // GROUP by statement

Null, // HAVING statement

StrOrderby // order by statement

);

}

 

/**

* List query with 2

* @ Param SQL: directly query input SQL statements

* @ Return Data Pointer

*/

Public Cursor getAll (String SQL ){

Return db. rawQuery (SQL, null );

}

/**

* Single data query 1

* @ Param rowId: Data id

* @ Param tableName: Table Name

* @ Param key keyword

* @ Param strCols column name

* @ Param strWhere Condition

* @ Param strGroupby Group

* @ Param strOrderby sorting

* @ Return a Single Data Pointer

*/

Public Cursor get (long rowId, String tableName, String key, String [] strCols, String strWhere, String strGroupby, String strOrderby ){

Cursor mCursor = db. query (

TableName,

StrCols,

Key + "=" + rowId,

Null, strGroupby, null, strOrderby );

// If the pointer exists, move the pointer to the first entry.

If (mCursor! = Null)

MCursor. moveToFirst ();

Return mCursor;

}

/**

* Single data query 2

* @ Param SQL: directly query input SQL statements

* @ Return a Single Data Pointer

*/

Public Cursor get (String SQL ){

Cursor mCursor = db. rawQuery (SQL, null );

// If the pointer exists, move the pointer to the first entry.

If (mCursor! = Null)

MCursor. moveToFirst ();

Return mCursor;

}

/**

* Update data

* @ Param rowId: Data id

* @ Param tableName: Table Name

* @ Param key update the column name

* @ Param args update data

* @ Return indicates whether the update is successful.

*/

Public boolean update (long rowId, String tableName, String key, ContentValues args ){

Return db. update (tableName, args, key + "=" + rowId, null)> 0;

}

/**

* Insert new data

* @ Param tableName: Table Name

* @ Param args data

* @ Return id is returned for success and-1 is returned for failure.

*/

Public long create (String tableName, ContentValues args ){

// Table name, not important, content value

Return db. insert (tableName, null, args );

}

/**

* Delete data

* @ Param rowId: Data id

* @ Param tableName: Table Name

* @ Param key keyword

* @ Return: whether the deletion is successful

*/

Public boolean delete (long rowId, String tableName, String key ){

Return db. delete (tableName, key + "=" + rowId, null)> 0;

}

/**

* @ Name DBTool internal class, used to create and update databases

* @ Author zhang. yue

* @ Create_date 2011-11-15

* @ Last_edit_author

* @ Last_edit_date

* @ Remark

* @ Edit_remark

*/

Public static class DatabaseHelper extends SQLiteOpenHelper {

/**

* Constructor

* @ Param context Data

*/

Public DatabaseHelper (Context context ){

// Object, database name, complex query, database version

Super (context, DBFinals. DATABASE_NAME, null, DBFinals. DBTABASE_VERSION );

}

/**

* Override the onCreate method to create a database.

*/

@ Override

Public void onCreate (SQLiteDatabase db ){

Db.exe cSQL (DBFinals. DBUser. DATABASE_TABLE_USER_CREATE );

}

/**

* Override the onUpgrade method and update the database based on the version number (DBTABASE_VERSION ).

*/

@ Override

Public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion ){

Db.exe cSQL ("drop table if exists" + DBFinals. DBUser. DATABASE_TABLE_USER );

OnCreate (db );

}

}

}

 

 

 

1. In this class, there is an internal class called DatabaseHelper, inherited from SQLiteOpenHelper. SQLiteOpenHelper is a basic class that Google has prepared for us to connect to and create databases. We only need to override the onCreate and onUpgrade methods to create a database and update the database based on the version number. The database creation statement is stored in DBFinals. DBUser. DATABASE_TABLE_USER_CREATE as a constant.

 

 

 

2. The DBTool class is used for database operations.

 

① Open method: Create a DatabaseHelper object and create or update a database. The getWritableDatabase method is used to create a database if the database does not exist. Otherwise, the database is updated based on the version.

 

 

 

② Close method: Close the connection established by the DatabaseHelper object.

 

 

 

③ GetAll method: query list. This method is reloaded here. One is the query method that comes with the SQLiteDatabase object. It can be seen that different parameters are passed in, which is similar to Hibernate or Linq. Another method of rawQuery is to query based on SQL statements. To be honest, use the latter more! The two methods return Cursor-type pointers. You must use the cusor. mCursor. moveToNext () mobile pointer to obtain data.

 

 

 

④ Get method: similar to querying the list, but here the first data of the returned pointer is taken out directly, instead of returning the entire Cursor pointer list. You can use either of the following methods.

 

 

 

⑤ Update method: update data using the update method inherent to the SQLiteDatabase object. You must pass parameters according to the specifications and return a Boolean value.

 

 

 

⑥ Create method: similar to the update method, the returned data id is the created data id, and-1 is returned for failure.

 

 

 

7. delete method: similar to update method.

 

 

 

We will discuss the specific call method in future foreground operations, but eager friends can try it directly. Basically, they are some of the more common methods in the Network and various tutorials.

 

From bad boy

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.