Android database Summary
To sum up the android database, Step 1: compile a class to inherit from SQLiteOpenHelper, as shown below:
package com.example.wxj2048;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class Dbdao extends SQLiteOpenHelper{private static final String DBNAME = "mldn.db";private static final int DBVERSION = 1;private static final String TABNAME = "game2048";public Dbdao(Context context){super(context, DBNAME, null, DBVERSION);}@Overridepublic void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stubString sql =" CREATE TABLE "+ TABNAME+" (" +" id INTEGER ," +" score INTEGER "+") ";db.execSQL(sql);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stubString sql = " DROP TABLE IF EXISTS " + TABNAME;db.execSQL(sql);this.onCreate(db);}public void insert(Integer score){SQLiteDatabase db = getWritableDatabase();ContentValues values = new ContentValues();values.put("id", 1);values.put("score", score);db.insert(TABNAME, null, values);db.close();}public void delete(){SQLiteDatabase db = getWritableDatabase();String[] data = new String[1]; data[0] = "1";db.delete(TABNAME,"id = ?",data);db.close();}public Integer query(){SQLiteDatabase db = getWritableDatabase();Cursor c = db.query(TABNAME, null, null, null, null, null, null); c.moveToFirst();int index = c.getColumnIndex("score");String result = c.getString(index);db.close();return Integer.valueOf(result);}}
Step 2: Create a Dbdao object and then use the database
Let's summarize the important methods of Cursor.
Close ()
Close the cursor to release resources
GetColumnCount ()
Returns the total number of all columns.
GetColumnIndex (String columnName)
Returns the name of the specified column. If no Column exists,-1 is returned.
GetColumnName (int columnIndex)
Returns the column name from the given index.
GetColumnNames ()
Returns the column name of a string array.
GetCount ()
Returns the number of rows in Cursor.
MoveToFirst ()
Move the cursor to the first line
MoveToLast ()
Move the cursor to the last line
MoveToNext ()
Move the cursor to the next row
Access the subscript of Cursor to obtain the data.
Int nameColumnIndex = cur. getColumnIndex (People. NAME );
String name = cur. getString (nameColumnIndex );