Android SQLite Google 官方用法

原创 2016年06月02日 00:06:31

SQL官方用法

Saving data to a database is ideal for repeating or structured data, such as contact information.The APIs you’ll need to use a database on Android are available in the android.database.sqlite package.

Define a Schema and Contract(计划和契约)

One of the main principles of SQL databases is the schema: a formal declaration of how the database is organized. The schema is reflected in the SQL statements that you use to create your database. You may find it helpful to create a companion class, known as a contract class, which explicitly specifies the layout of your schema in a systematic and self-documenting way.

A contract class is a container for constants that define names for URIs, tables, and columns. The contract class allows you to use the same constants across all the other classes in the same package. This lets you change a column name in one place and have it propagate throughout your code.

A good way to organize a contract class is to put definitions that are global to your whole database in the root level of the class. Then create an inner class for each table that enumerates its columns.

Note: By implementing the BaseColumns interface, your inner class can inherit a primary key field called _ID that some Android classes such as cursor adaptors will expect it to have. It’s not required, but this can help your database work harmoniously with the Android framework.

public final class StudentContract {

    // To prevent someone from accidentally instantiating the contract class,
    // give it an empty constructor.
    public StudentContract(){
    }

    /* Inner class that defines the table contents */
    public static abstract class StudentEntry implements BaseColumns{
        public static final String TABLE_NAME="entry";
        public static final String COLUMN_NAME_ENTRY_ID="entryid";
        public static final String COLUMN_NAME_NAME="name";
        public static final String COLUMN_NAME_AGE="age";
        public static final String COLUMN_NAME_HEIGHT="height";
    }
}

Create a Database Using a SQL Helper

Once you have defined how your database looks, you should implement methods that create and maintain the database and tables. Here are some typical statements that create and delete a table:

private static final String TEXT_TYPE=" TEXT";
private static final String INTEGER_TYPE=" INTEGER";
private static final String COMMA_SEP=",";
private static final String SQL_CREATE_ENTRY="CREATE TABLE if not exits "+
        StudentContract.StudentEntry.TABLE_NAME+" ("+
        StudentContract.StudentEntry.COLUMN_NAME_ENTRY_ID+" INTEGER PRIMARY KEY,"+
        StudentContract.StudentEntry.COLUMN_NAME_NAME+TEXT_TYPE+COMMA_SEP+
        StudentContract.StudentEntry.COLUMN_NAME_AGE+INTEGER_TYPE+COMMA_SEP+
        StudentContract.StudentEntry.COLUMN_NAME_HEIGHT+INTEGER_TYPE+" )";

private static final String SQL_DELETE_INTRIES="DROP TABLE IF EXISTS "+
        StudentContract.StudentEntry.TABLE_NAME;

Just like files that you save on the device’s internal storage, Android stores your database in private disk space that’s associated application. Your data is secure, because by default this area is not accessible to other applications.

A useful set of APIs is available in the SQLiteOpenHelper class. When you use this class to obtain references to your database, the system performs the potentially long-running operations of creating and updating the database only when needed and not during app startup. All you need to do is call getWritableDatabase() or getReadableDatabase().

Note: Because they can be long-running, be sure that you call getWritableDatabase() or getReadableDatabase() in a background thread, such as with AsyncTask or IntentService.

To use SQLiteOpenHelper, create a subclass that overrides the onCreate(), onUpgrade() and onOpen() callback methods. You may also want to implement onDowngrade(), but it’s not required.

public class DBHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION=1;
    private static final String DATABASE_NAME="studentInfo.db";

    public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRY);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // This database is only a cache for online data, so its upgrade policy is
        // to simply to discard the data and start over
        if(oldVersion>newVersion) return;
        db.execSQL(SQL_DELETE_INTRIES);
        onCreate(db);
    } 
}

To access your database, instantiate your subclass of SQLiteOpenHelper:

 DBHelper mdbHelper=new DBHelper(MainActivity.this);

Put Information into a Database

insert data into the database by passing a ContentValues object to the insert() method:

// Gets the data repository in write mode
SQLiteDatabase db=mdbHelper.getWritableDatabase();

// Create a new map of values, where column names are the keys
ContentValues values=new ContentValues();
values.put(StudentContract.StudentEntry.COLUMN_NAME_ENTRY_ID,1);
values.put(StudentContract.StudentEntry.COLUMN_NAME_NAME,"Eric");
values.put(StudentContract.StudentEntry.COLUMN_NAME_AGE,"20");
values.put(StudentContract.StudentEntry.COLUMN_NAME_HEIGHT,"130");

// Insert the new row, returning the primary key value of the new row
long newRowId=db.insert(StudentContract.StudentEntry.TABLE_NAME,
        StudentContract.StudentEntry.COLUMN_NAME_NULLABLE,values);

The first argument for insert() is simply the table name. The second argument provides the name of a column in which the framework can insert NULL in the event that the ContentValues is empty (if you instead set this to “null”, then the framework will not insert a row when there are no values).

Read Information from a Database

To read from a database, use the query() method, passing it your selection criteria and desired columns. The method combines elements of insert() and update(), except the column list defines the data you want to fetch, rather than the data to insert. The results of the query are returned to you in a Cursor object.

SQLiteDatabase db=mdbHelper.getReadableDatabase();

// Define a projection that specifies which columns from the database
// you will actually use after this query.
String []projection={
        StudentContract.StudentEntry.COLUMN_NAME_ENTRY_ID,
        StudentContract.StudentEntry.COLUMN_NAME_NAME,
        StudentContract.StudentEntry.COLUMN_NAME_AGE,
        StudentContract.StudentEntry.COLUMN_NAME_HEIGHT
};

// How you want the results sorted in the resulting Cursor
String sortOrder="age"+" DESC";

Cursor cursor=db.query(
        StudentContract.StudentEntry.TABLE_NAME,    // The table to query
        projection,                                 // The columns to return
        "time" + "=?",                              // The columns for the WHERE clause
        new String[]{"20"},                         // The values for the WHERE clause
        null,                                       // don't group the rows
        null,                                       // don't filter by row groups
        sortOrder                                   // The sort order
);

To look at a row in the cursor, use one of the Cursor move methods, which you must always call before you begin reading values. Generally, you should start by calling moveToFirst(), which places the “read position” on the first entry in the results. For each row, you can read a column’s value by calling one of the Cursor get methods, such as getString() or getLong(). For each of the get methods, you must pass the index position of the column you desire, which you can get by calling getColumnIndex() or getColumnIndexOrThrow().

cursor.moveToFirst();
String name=cursor.getString(cursor.getColumnIndex("name"));
System.out.println(name);

Delete Information from a Database

To delete rows from a table, you need to provide selection criteria that identify the rows. The database API provides a mechanism for creating selection criteria that protects against SQL injection. The mechanism divides the selection specification into a selection clause and selection arguments. The clause defines the columns to look at, and also allows you to combine column tests. The arguments are values to test against that are bound into the clause. Because the result isn’t handled the same as a regular SQL statement, it is immune to SQL injection.

// Define 'where' part of query.
String selection= StudentContract.StudentEntry.COLUMN_NAME_NAME+" LIKE ?";
// Specify arguments in placeholder order.
String selectionArgs[]={"Eric"};
// Issue SQL statement.
db.delete(StudentContract.StudentEntry.TABLE_NAME,
        selection,selectionArgs);

Update a Database

When you need to modify a subset of your database values, use the update() method.
Updating the table combines the content values syntax of insert() with the where syntax of delete().

// New value for one column
ContentValues contentValues=new ContentValues();
contentValues.put(StudentContract.StudentEntry.COLUMN_NAME_NAME,"Eric2");

// Which row to update, based on the ID
String selection= StudentContract.StudentEntry.COLUMN_NAME_ENTRY_ID+" LIKE ?";
String []selectionArgs={String.valueOf(1)};

int count=db.update(
        StudentContract.StudentEntry.TABLE_NAME,
        contentValues,
        selection,
        selectionArgs
);
版权声明:本文为博主原创文章,未经博主允许不得转载。

Google 官方Android MVP架构实践

一、Google 官方MVP介绍 近期,关于Android开发架构的讨论沸沸扬扬,各大技术平台随处可见关于Android架构的技术文章。MVC、MVP、MVVM等等,就目前的形式来看,MVP模式在An...
  • u011459799
  • u011459799
  • 2016年05月10日 11:11
  • 11883

图解Google官方示例的各种android框架

Goolge官方的Android框架源码见:GitHub工程; 毋庸置疑,官方给出的框架示例应该是最标准也最具有普适性的。本文根据工程中的示例,画出了各个框架的架构图,以方便快速学习和了解。 1。...
  • chwnpp2
  • chwnpp2
  • 2017年04月05日 18:04
  • 693

谷歌官方Android应用架构库——App 架构指南

谷歌官方Android应用架构库——App 架构指南
  • hubinqiang
  • hubinqiang
  • 2017年06月11日 04:57
  • 3507

Google官方提供的有用的Android范例程序,值得学习的新技术

原文,Google官方blog。 http://android-developers.blogspot.sg/2015/04/new-android-code-samples.html ...
  • birdsaction
  • birdsaction
  • 2015年04月24日 15:09
  • 10251

Android的Google官方设计指南(上)

[+] Android 设计规范 时间 2015.3.2版本 V1.0翻译 杨鹏整理 赵凯强 本文章是我公司一个大牛之前的公司同事翻译的Android的Google官方设计指导,经过我整...
  • lsyz0021
  • lsyz0021
  • 2016年04月28日 01:28
  • 1698

Google官方支持的MVVM架构框架Data Binding使用入门

转载地址:http://blog.csdn.net/wqc_csdn/article/details/53399737 最新最新推出的MVVM架构是将MVP中的Presenter...
  • l_215851356
  • l_215851356
  • 2017年03月12日 16:16
  • 609

再论Android最新架构—Google 官方Android开发新架构指南

简评:虽然说 Android 的架构选择一直都很自由,MVP、MVC、MVVM 各有拥趸。但 Google 最近还是推出了一份关于应用架构的实践指南,并给出了相当详尽的步骤和一些指导建议。希望大家都能...
  • wangwangli6
  • wangwangli6
  • 2017年06月09日 12:19
  • 1504

Google包装的SQLite的增删改查

public class CopyOfPersonDao { private SQLiteOpenHelper helper; /** * 在构造方法里完成helper的初始化 */ ...
  • oyty892968
  • oyty892968
  • 2013年08月20日 20:52
  • 948

Google官方Android性能优化典范第3季

原文转自:http://www.cnblogs.com/yezhennan/p/5443580.html (1)Fun with ArrayMaps 程序内存的管理是否合理高效对应用的...
  • true100
  • true100
  • 2016年09月08日 15:51
  • 1505

google官方架构MVP解析与实战-(从零开始搭建android框架系列(3))

最近更新2016.5.10(已经添加整个项目目录。更新新闻资讯) 本篇文章项目github地址:MVPCommon 本文章原地址:简书博客1 前言当然对于MVP的解说也是使用也是层出不穷,我也网络...
  • u014315849
  • u014315849
  • 2016年05月12日 16:45
  • 6395
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Android SQLite Google 官方用法
举报原因:
原因补充:

(最多只允许输入30个字)