您的位置:首页 > 移动开发 > Android开发

Using SQLite in android demo

2011-10-19 11:16 483 查看
1.in android,you can using SQLite save data,as flowing exampe:

package tuo.test;

import tuo.test.entity.UserProfile;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class GucSQLite extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "GucNightingale.db";
private static final String TABLE_NAME = "nurse_app_setting";
private static final int DATABASE_VERSION = 1;

String TAG = "GucSQLite";

public GucSQLite(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase database) {
String creat_sql = "CREATE TABLE "
+ TABLE_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT,mobile TEXT,appid TEXT,pwd TEXT,dept TEXT,his_account TEXT)";
database.execSQL(creat_sql);
}

@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
database.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
onCreate(database);
}

public UserProfile getUserProfile() {
UserProfile userProfile = null;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] { "id", "appid","mobile", "pwd", "dept", "his_account" }, null, null, null,null, null);
while (cursor.moveToNext()) {
userProfile = new UserProfile();
userProfile.setId(cursor.getString(0));
userProfile.setAppid(cursor.getString(1));
userProfile.setMobile(cursor.getString(2));
userProfile.setPwd(cursor.getString(3));
userProfile.setDept(cursor.getString(4));
userProfile.setHis_account(cursor.getString(5));
}
return userProfile;
}

public boolean saveOrUpdateUserProfile(UserProfile user) {
int result;
ContentValues values = new ContentValues();
values.put("appid", user.getAppid());
values.put("mobile", user.getMobile());
values.put("pwd", user.getPwd());
values.put("dept", user.getDept());
values.put("his_account", user.getHis_account());
if (isExist(user)) {
String whereClause = "mobile =?";
String[] whereArgs = new String[] { user.getMobile() };
result = (int) this.getWritableDatabase().update(TABLE_NAME,values, whereClause, whereArgs);
} else {
result = (int) this.getWritableDatabase().insertOrThrow(TABLE_NAME,null, values);
}
return result > 0;
}

private boolean isExist(UserProfile user) {
return this.getReadableDatabase()
.rawQuery("SELECT id FROM " + TABLE_NAME + " WHERE mobile="+ user.getMobile(), null).getCount() > 0;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: