1. 程式人生 > >SQLite資料庫儲存

SQLite資料庫儲存

package com.wzxy.sqlitetest;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
/**
* Created by prx on 2015/12/29.
*/
public class MySQLiteHelper {//用來管理資料庫的類
private MySQLiteManager manager;
public MySQLiteHelper(Context context) {
//建立管理資料庫的類的物件
manager = new MySQLiteManager(context);
}

// 插入
public void insert(String title, String content, String type, long time) {
String sql = "insert into news(title,content,type,time) values(?,?,?,?);";
SQLiteDatabase db = manager.getReadableDatabase();
db.execSQL(sql, new Object[]{title, content, type,
time});
db.close();
}

// 刪除
public void delete(int id) {
String sql = "delete from news where _id = ?";
SQLiteDatabase db = manager.getWritableDatabase();
db.execSQL(sql, new Object[]{id});
db.close();
}

// 修改
/*
* id:修改條件 title:修改內容
*/
public void upData(int id, String title) {
String sql = "update news set title = ? where _id = ?"
;
SQLiteDatabase db = manager.getReadableDatabase();
db.execSQL(sql, new Object[]{title, id});
db.close();
}

// 查詢
public void selectAll() {
String sql = "select * from news";
SQLiteDatabase db = manager.getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);
int count = cursor.getCount();
while (cursor.moveToNext()) {
String title = cursor.getString(cursor.getColumnIndex("title"));
String content = cursor.getString(cursor.getColumnIndex("content"));
String type = cursor.getString(cursor.getColumnIndex("type"));
String time = cursor.getString(cursor.getColumnIndex("time"));
Log.i("Data", "title:" + title + ",content:" + content
+ ",type:" + type + ",time:" + time);
}
}

//分頁查詢
public void select(int id) {
SQLiteDatabase db = manager.getReadableDatabase();
int count = db.rawQuery("select * from news", null).getCount();
int page = count / 20 + count % 20 > 0 ? 1 : 0;
String sql = null;
if (id + 20 > count && id < count) {
sql = "select * from news limit " + id + "," + (count - id);
} else if (id + 20 < count) {
sql = "select * from news limit " + id + ",20";
}

Cursor cursor = db.rawQuery(sql, null);
while (cursor.moveToNext()) {
String title = cursor.getString(cursor.getColumnIndex("title"));
String content = cursor.getString(cursor.getColumnIndex("content"));
String type = cursor.getString(cursor.getColumnIndex("type"));
String time = cursor.getString(cursor.getColumnIndex("time"));
Log.i("=-Data-=", "title:" + title + ",content:" + content
+ ",type:" + type + ",time:" + time);
}
}
}