享受Android应用程序的Java技术盛宴
2010-10-27 21:24:37 来源:Web开发网Android 数据库连通性
Android 中一个非常有用的特征就是存在本地关系数据库。保证您能在本地文件中存储您的数据,但通常更有用的是使用一个关系型数据库管理系统(Relational Database Management System,RDBMS)来存储。Android 提供给您常用的 SQLite 数据库来进行处理,因为对于像 Android 这类嵌入式系统它是高度优化的。它被 Android 上的核心应用程序所用。例如,用户地址簿是存储在一个 SQLite 数据库中。现在,对于给定的 Android 的 Java 实现,您可以使用 JDBC 来访问这些数据库。出人意料的是,Android 甚至包括构成主要部分 JDBC API 的 java.sql 和 javax.sql 包。然而,当涉及使用本地 Android 数据库进行处理时,这毫无用处。相反地,您想要使用 android.database 和 android.database.sqlite 包。清单 5 是一个使用这些类存储和检索数据的示例。
清单 5. 使用 Android 进行数据库访问
public class StocksDb {
private static final String DB_NAME = "stocks.db";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "stock";
private static final String CREATE_TABLE = "CREATE TABLE " +
TABLE_NAME + " (id INTEGER PRIMARY KEY, symbol TEXT, max_price DECIMAL(8,2), " +
"min_price DECIMAL(8,2), price_paid DECIMAL(8,2), " +
"quantity INTEGER)";
private static final String INSERT_SQL = "INSERT INTO " + TABLE_NAME +
" (symbol, max_price, min_price, price_paid, quantity) " +
"VALUES (?,?,?,?,?)";
private static final String READ_SQL = "SELECT id, symbol, max_price, " +
"min_price, price_paid, quantity FROM " + TABLE_NAME;
private final Context context;
private final SQLiteOpenHelper helper;
private final SQLiteStatement stmt;
private final SQLiteDatabase db;
public StocksDb(Context context){
this.context = context;
helper = new SQLiteOpenHelper(context, DB_NAME, null,
DB_VERSION){
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
throw new UnsupportedOperationException();
}
};
db = helper.getWritableDatabase();
stmt = db.compileStatement(INSERT_SQL);
}
public Stock addStock(Stock stock){
stmt.bindString(1, stock.getSymbol());
stmt.bindDouble(2, stock.getMaxPrice());
stmt.bindDouble(3, stock.getMinPrice());
stmt.bindDouble(4, stock.getPricePaid());
stmt.bindLong(5, stock.getQuantity());
int id = (int) stmt.executeInsert();
return new Stock (stock, id);
}
public ArrayList<Stock> getStocks() {
Cursor results = db.rawQuery(READ_SQL, null);
ArrayList<Stock> stocks =
new ArrayList<Stock>(results.getCount());
if (results.moveToFirst()){
int idCol = results.getColumnIndex("id");
int symbolCol = results.getColumnIndex("symbol");
int maxCol = results.getColumnIndex("max_price");
int minCol = results.getColumnIndex("min_price");
int priceCol = results.getColumnIndex("price_paid");
int quanitytCol = results.getColumnIndex("quantity");
do {
Stock stock = new Stock(results.getString(symbolCol),
results.getDouble(priceCol),
results.getInt(quanitytCol),
results.getInt(idCol));
stock.setMaxPrice(results.getDouble(maxCol));
stock.setMinPrice(results.getDouble(minCol));
stocks.add(stock);
} while (results.moveToNext());
}
if (!results.isClosed()){
results.close();
}
return stocks;
}
public void close(){
helper.close();
}
}
更多精彩
赞助商链接