package com.example.utils;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
/**
*
* 用于存储splist的数据
*
* @author 陈滨
*
*/
public class DBHelper extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "USERS";//数据库名称
private final static int DATABASE_VERSION = 1;//数据库版本
private final static String TABLE_NAME = "USER_INFO";//数据库表名
private final static String FIELD_ID = "_id";//编号
private final static String FIELD_NAME ="NAME";//名称
private final static String FIELD_PASS="PASS";//密码
private final static String FIELD_HEAD="HEAD";//头像
private SQLiteDatabase db;//数据
@Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
db = this.getWritableDatabase();
String sql = "Create table %s (%s integer primary key autoincrement,%s text,%s text,%s text);";
sql = String.format(sql, TABLE_NAME, FIELD_ID, FIELD_NAME,FIELD_PASS,FIELD_HEAD);
db.execSQL(sql);
}
/**
* 查询所有的数据根据id排序
* @return
*/
public Cursor select() {
db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null,
FIELD_ID);
return cursor;
}
/** 注册的时候调用,返回受影响行数
* @param name 用户名
* @param pass 密码
* @param head 头像地址
* @return
*/
public long insert(String name,String pass,String head) {
db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(FIELD_NAME, name);
cv.put(FIELD_PASS, pass);
cv.put(FIELD_HEAD, head);
long row = db.insert(TABLE_NAME, null, cv);
return row;
}
/**
* 根据id编号删除一行数据
* @param id 编号
*/
public void delete(int id){
db = this.getWritableDatabase();
String where = FIELD_ID + "= ?";
String[] wherevalue = {Integer.toString(id)};
db.delete(TABLE_NAME, where, wherevalue);
}
/**
* 根据编号来更新用信息
* @param id 编号
* @param name 名称
* @param pass 密码
* @param head 头像
*/
public void update(int id,String name,String pass,String head)
{
db = this.getWritableDatabase();
String where = FIELD_ID + "= ?";
String[] wherevalue = {Integer.toString(id)};
ContentValues cv = new ContentValues();
cv.put(FIELD_NAME, name);
cv.put(FIELD_PASS, pass);
cv.put(FIELD_HEAD, head);
db.update(TABLE_NAME, cv, where, wherevalue);
}
/**
* 一个参数的构造方法
* @param context 上下文对象
*/
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
db=getWritableDatabase();
String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;
db.execSQL(sql);
onCreate(db);
}
public DBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
}
安卓sqllitehelper 继承SQLiteOpenHelper
最新推荐文章于 2024-08-25 22:46:29 发布