Книга: Beginning Android

Makin’ Data

Makin’ Data

Given that you have a database and one or more tables, you probably want to put some data in them and such. You have two major approaches for doing this.

You can always use execSQL(), just like you did for creating the tables. The execSQL() method works for any SQL that does not return results, so it can handle INSERT, UPDATE, DELETE, etc. just fine. So, for example you could use this code:

db.execSQL("INSERT INTO widgets (name, inventory)" +
 VALUES ('Sprocket', 5));

Your alternative is to use the insert(), update(), and delete() methods on the SQLiteDatabase object. These are “builder” sorts of methods, in that they break down the SQL statements into discrete chunks, then take those chunks as parameters.

These methods make use of ContentValues objects, which implement a Map-esque interface, albeit one that has additional methods for working with SQLite types. For example, in addition to get() to retrieve a value by its key, you have getAsInteger(), getAsString(), and so forth.

The insert() method takes the name of the table, the name of one column as the null column hack, and a ContentValues with the initial values you want put into this row. The null column hack is for the case where the ContentValues instance is empty — the column named as the null column hack will be explicitly assigned the value NULL in the SQL INSERT statement generated by insert().

ContentValues cv = new ContentValues();
cv.put(Constants.TITLE, "Gravity, Death Star I");
cv.put(Constants.VALUE, SensorManager.GRAVITY_DEATH_STAR_I);
db.insert("constants", getNullColumnHack(), cv);

The update() method takes the name of the table, a ContentValues representing the columns and replacement values to use, an optional WHERE clause, and an optional list of parameters to fill into the WHERE clause, to replace any embedded question marks (?). Since update() replaces only columns with fixed values, versus ones computed based on other information, you may need to use execSQL() to accomplish some ends.

The WHERE clause and parameter list work akin to the positional SQL parameters you may be used to from other SQL APIs. Consider this example:

// replacements is a ContentValues instance
String[] parms = new String[] {"snicklefritz"};
db.update("widgets", replacements, "name=?", parms);

The delete() method works akin to update(), taking the name of the table, the optional WHERE clause, and the corresponding parameters to fill into the WHERE clause.

Оглавление книги

Генерация: 0.386. Запросов К БД/Cache: 3 / 1
Вверх Вниз