Android 数据存储之 SQLite嵌入式数据库
2010-03-26 15:43:00 来源:WEB开发网// 仅演示用,所以先删除表然后再创建。
db.execSQL("DROP TABLE IF EXISTS contacts");
this.onCreate(db);
}
}
4.编写ContactsService类
ContactsService类主要实现对业务逻辑和数据库的操作。
package com.changcheng.sqlite.service;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import com.changcheng.sqlite.MyOpenHelper;
import com.changcheng.sqlite.entity.Contact;
public class ContactsService {
private MyOpenHelper openHelper;
public ContactsService(Context context) {
this.openHelper = new MyOpenHelper(context);
}
/**
* 保存
*
* @param contact
*/
public void save(Contact contact) {
String sql = "INSERT INTO contacts (name, phone) VALUES (?, ?)";
Object[] bindArgs = { contact.getName(), contact.getPhone() };
this.openHelper.getWritableDatabase().execSQL(sql, bindArgs);
}
/**
* 查找
*
* @param id
* @return
*/
public Contact find(Integer id) {
String sql = "SELECT _id,name, phone FROM contacts WHERE _id=?";
String[] selectionArgs = { id + "" };
Cursor cursor = this.openHelper.getReadableDatabase().rawQuery(sql,
selectionArgs);
if (cursor.moveToFirst())
return new Contact(cursor.getInt(0), cursor.getString(1), cursor
.getString(2));
return null;
}
/**
* 更新
*
* @param contact
*/
public void update(Contact contact) {
String sql = "UPDATE contacts SET name=?, phone=? WHERE _id=?";
Object[] bindArgs = { contact.getName(), contact.getPhone(),
更多精彩
赞助商链接