前端之家收集整理的这篇文章主要介绍了
Sqlite简单尝试,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package com.ine.db.impl;
import android.content.Context;
import android.database.sqlite.sqliteDatabase;
import android.database.sqlite.sqliteOpenHelper;
public class DBHelper extends sqliteOpenHelper {
private static final String DATABASE_NAME = "test.db";
private static final int DATABASE_VERSION = 1;
public DBHelper(Context context)
{
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(sqliteDatabase db)
{
db.execsql("CREATE TABLE IF NOT EXISTS count"
+ "(data_id INTEGER PRIMARY KEY AUTOINCREMENT,date TEXT,type TEXT)");
}
@Override
public void onUpgrade(sqliteDatabase db,int oldVersion,int newVersion)
{
db.execsql("ALTER TABLE count ADD COLUMN other STRING");
}
}@H_301_81@
package com.ine.db.impl;
import java.util.ArrayList;
import java.util.List;
import com.ine.entity.CrtData;
import com.ine.tool.CrtTool;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.sqliteDatabase;
public class DBManager {
private DBHelper dbh;
private sqliteDatabase db;
public DBManager(Context context)
{
dbh = new DBHelper(context);
db = dbh.getWritableDatabase();
}
public boolean save(long date,String type)
{
long resoult = -1;
db.beginTransaction();
try
{
ContentValues cv = new ContentValues();
cv.put("date",date);
cv.put("type",type);
resoult = db.insert("count",cv);
db.setTransactionSuccessful();
} finally
{
db.endTransaction();
}
return (-1 < resoult) ? true : false;
}
public List<CrtData> getAll()
{
Cursor c = db.rawQuery("SELECT * FROM count",null);
return getByCursor(c);
}
public List<CrtData> getByType(String type)
{
Cursor c =
db.rawQuery("SELECT * FROM count WHERE type = ?",new String[]
{ type });
return getByCursor(c);
}
public void delAll()
{
db.execsql("DELETE FROM count;");
}
private List<CrtData> getByCursor(Cursor c)
{
ArrayList<CrtData> datas = new ArrayList<CrtData>();
while (c.moveToNext())
{
CrtData data = new CrtData();
data.setData_id(c.getInt(c.getColumnIndex("data_id")));
data.setDate(c.getString(c.getColumnIndex("date")));
data.setType(c.getString(c.getColumnIndex("type")));
datas.add(CrtTool.initCrtData(data));
}
c.close();
return datas;
}
/** * close database */
public void closeDB()
{
db.close();
}
}@H_301_81@