微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

WORKING WITH SQLite DATABASES

Skeleton code for a standard database adapter implementation

import android.content.Context;
import android.database.*;
import android.database.sqlite.*;
import android.database.sqlite.sqliteDatabase.CursorFactory;
import android.util.Log;
public class MyDBAdapter {
private static final String DATABASE_NAME = "myDatabase.db";
private static final String DATABASE_TABLE = "mainTable";
private static final int DATABASE_VERSION = 1;
// The index (key) column name for use in where clauses.
public static final String KEY_ID="_id";
// The name and column index of each column in your database.
public static final String KEY_NAME="name";
public static final int NAME_COLUMN = 1;
// Todo: Create public field for each column in your table.
// sql Statement to create a new database.
private static final String DATABASE_CREATE = "create table " +
DATABASE_TABLE + " (" + KEY_ID +
" integer primary key autoincrement," +
KEY_NAME + " text not null);";
// Variable to hold the database instance
private sqliteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private myDbHelper dbHelper;

public MyDBAdapter(Context _context) {
context = _context;
dbHelper = new myDbHelper(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public MyDBAdapter open() throws sqlException {
db = dbHelper.getWritableDatabase();
return this;
}

public void close() {
db.close();
}
public int insertEntry(MyObject _myObject) {
// Todo: Create a new ContentValues to represent my row
// and insert it into the database.
return index;
}
public boolean removeEntry(long _rowIndex) {
return db.delete(DATABASE_TABLE,KEY_ID + "=" + _rowIndex,null) > 0;
}
public Cursor getAllEntries () {
return db.query(DATABASE_TABLE,new String[] {KEY_ID,KEY_NAME},
null,null);
}
public MyObject getEntry(long _rowIndex) {
// Todo: Return a cursor to a row from the database and
// use the values to populate an instance of MyObject
return objectInstance;
}

public boolean updateEntry(long _rowIndex,MyObject _myObject) {
// Todo: Create a new ContentValues based on the new object
// and use it to update a row in the database.
return true;
}
private static class myDbHelper extends sqliteOpenHelper {
public myDbHelper(Context context,String name,
CursorFactory factory,int version) {
super(context,name,factory,version);
}
// Called when no database exists in disk and the helper class needs
// to create a new one.
@Override
public void onCreate(sqliteDatabase _db) {
_db.execsql(DATABASE_CREATE);
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
@Override
public void onUpgrade(sqliteDatabase _db,int _oldVersion,int _newVersion) {
// Log the version upgrade.
Log.w("TaskDBAdapter","Upgrading from version " +
_oldVersion + " to " +
_newVersion + ",which will destroy all old data");

// Upgrade the existing database to conform to the new version. Multiple
// prevIoUs versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execsql("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Create a new one.
onCreate(_db);
}
}
}

Introducing the sqliteOpenHelper

sqliteOpenHelper is an abstract class used to implement the best practice pattern for creating,opening,
and upgrading databases. By implementing an sqlite Open Helper you hide the logic used to decide if
a database needs to be created or upgraded before it’s opened.

Call getReadableDatabase or getWritableDatabase to open and return a readable/writable instance of
the underlying database.A call to getWritableDatabase can fail because of disk space or permission issues,so it’s good practice
to provide fallback to the getReadableDatabase method

dbHelper = new myDbHelper(context,DATABASE_VERSI
sqliteDatabase db;
try {
db = dbHelper.getWritableDatabase();
}
catch (sqliteException ex){
db = dbHelper.getReadableDatabase();
}

opening and Creating Databases without sqliteHelper

private static final String DATABASE_NAME = "myDatabase.db";
private static final String DATABASE_TABLE = "mainTable";
private static final String DATABASE_CREATE =
"create table " + DATABASE_TABLE + " ( _id integer primary key autoincrement," +
"column_one text not null);";
sqliteDatabase myDatabase;
private void createDatabase() {
myDatabase = openorCreateDatabase(DATABASE_NAME,Context.MODE_PRIVATE,null);
myDatabase.execsql(DATABASE_CREATE);
}

Querying a Database

// Return all rows for columns one and three,no duplicates
String[] result_columns = new String[] {KEY_ID,KEY_COL1,KEY_COL3};
Cursor allRows = myDatabase.query(true,DATABASE_TABLE,result_columns,null);
// Return all columns for rows where column 3 equals a set value
// and the rows are ordered by column 5.
String where = KEY_COL3 + "=" + requiredValue;
String order = KEY_COL5;
Cursor myResult = myDatabase.query(DATABASE_TABLE,where,order);

Inserting New Rows

// Create a new row of values to insert.
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(COLUMN_NAME,newValue);
[ ... Repeat for each column ... ]
// Insert the row into your table
myDatabase.insert(DATABASE_TABLE,newValues);

Updating a Row

// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
newValues.put(COLUMN_NAME,newValue);
[ ... Repeat for each column ... ]
String where = KEY_ID + "=" + rowId;
// Update the row with the specified index with the new values.
myDatabase.update(DATABASE_TABLE,newValues,null);

Deleting Rows

myDatabase.delete(DATABASE_TABLE,KEY_ID + "=" + rowId,null);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐