android数据库实例
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
package com.adrainy.webmarks;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentV alues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper {
public static final String _ID = "_id";
public static final String NAME = "name";
public static final String URL = "url";
public static final String DESC = "desc";
public static final String DA TABASE_NAME = "webBookmarksdata";
public static final String TABLE_NAME = "webmarks";
public static final int VERSION = 1;
public static final String DA TA TABLE_CREA TE = "create table " + TABLE_NAME + "(" + _ID + " integer primary key autoincrement , " + NAME
+ " text not null," + URL + " text not null," + DESC + " text)";
private SQLiteDatabase sqldb;
private MySQLHelper helper;
private Context ctx;
private ContentV alues values;
public DBHelper(Context context) {
this.ctx = context;
}
class MySQLHelper extends SQLiteOpenHelper {
public MySQLHelper() {
// 创建数据库和数据库版本号
super(ctx, DA TABASE_NAME, null, VERSION);
}
// 创建表
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DA TA TABLE_CREA TE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldV ersion, int newV ersion) { db.execSQL("drop table if exists " + TABLE_NAME);
onCreate(db);
}
}
// 打开数据库
public void open() {
helper = new MySQLHelper();
sqldb = helper.getWritableDatabase();
}
// 关闭数据库
public void close() {
helper.close();
}
// 添加记录
public int insert(Link link) {
values = new ContentV alues();
values.put(NAME, link.getName());
values.put(URL, link.getUrl());
values.put(DESC, link.getDesc());
return (int) sqldb.insert(TABLE_NAME, "empty", values);
// empty是表中没有指向的列时用empty代替
}
// 删除选中de记录
public int delete(int id) {
String[] whereArgs = { String.valueOf(id) };
return sqldb.delete(TABLE_NAME, "_id=?", whereArgs);
}
// 修改记录
public int update(Link link) {
values = new ContentV alues();
values.put(NAME, link.getName());
values.put(URL, link.getUrl());
values.put(DESC, link.getDesc());
String[] whereArgs = { String.valueOf(link.getId()) };
return sqldb.update(TABLE_NAME, values, _ID + "=?", whereArgs);
}