android 简单的单例模式数据库操作

来源:互联网 发布:小脑袋智能推广软件 编辑:程序博客网 时间:2024/04/30 08:52


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;


public class SqlHelper {
private static SqlHelper sqlhelper = null;
private Helper helper = null;// 数据库操作对象
private Context context = null;
static String name = "LENOVO.DB";// 数据库名称
static CursorFactory factory = null;
static int version = 1;
private static final String SQL_SUBSCRIBE_WEBSITE = "create table if not exists subscribe_website(anto_id integer primary key,website_id integer)";


public static synchronized SqlHelper getInstance(Context context) {


if (sqlhelper == null && context != null) {
sqlhelper = new SqlHelper(context);
}
return sqlhelper;
}


private SqlHelper(Context context) {
this.context = context;
if (null == helper)
helper = new Helper(context);
}


static class Helper extends SQLiteOpenHelper {
SQLiteDatabase database;


public Helper(Context context) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
database = getWritableDatabase();// 获得可操作的数据库对象
}


@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SQL_SUBSCRIBE_WEBSITE);


}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub


}


@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
}


}


public boolean insertSubscribeWebsite(int websiteId) {
try {
helper.database.execSQL(
"insert into subscribe_website(website_id)values(?)",
new Object[] { websiteId });
} catch (android.database.SQLException e) {
e.printStackTrace();
return false;
}
return true;
}


public List<Integer> selectSubscribeWebsiteId() {
Cursor cursor = null;
String sql = "select website_id from subscribe_website";
List<Integer> list = new ArrayList<Integer>();


try {
cursor = helper.database.rawQuery(sql, null);


if (cursor.moveToFirst()) {
do {
list.add(cursor.getInt(0));
} while (cursor.moveToNext());
}


} catch (android.database.SQLException e) {
e.printStackTrace();
return null;
}

return list;

}


public boolean deleteSubscribe(int id) {
boolean flag = true;
String sql = "delete from subscribe_website where website_id=" + "'"
+ id + "'";
try {
helper.database.execSQL(sql);
} catch (android.database.SQLException e) {
flag = false;
e.printStackTrace();
}
return flag;
}


}
原创粉丝点击