package cn.zhaoliang5156.zhaoliang2018727.db;
public class NewsBean {
public int _id;
public String url;
public String json;
public NewsBean() {
}
public NewsBean(String url, String json) {
this.url = url;
this.json = json;
}
}
public class NewsDao {
private NewsSqliteOpenHelper helper;
private SQLiteDatabase db;
public NewsDao(Context context) {
helper = new NewsSqliteOpenHelper(context);
db = helper.getWritableDatabase();
}
/**
* 插入或更新
*
* @param bean
*/
public void replace(NewsBean bean) {
ContentValues values = new ContentValues();
values.put("url", bean.url);
values.put("json", bean.json);
db.replace("news", null, values);
}
/**
* 查询
*
* @param url
* @return
*/
public NewsBean load(String url) {
NewsBean newsBean = null;
Cursor cursor = db.rawQuery("select * from news where url = ?", new String[]{url});
if (cursor.moveToNext()) {
newsBean = new NewsBean();
newsBean.url = cursor.getString(cursor.getColumnIndex("url"));
newsBean.json = cursor.getString(cursor.getColumnIndex("json"));
}
return newsBean;
}
}
/**
* 数据库帮助类
*/
public class NewsSqliteOpenHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "news.db";
private static final int DB_VERSION = 1;
public NewsSqliteOpenHelper(@Nullable Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table news(_id INTEGER primary key autoincrement, url TEXT, json TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}