Android SQLiteOpenHelper 对SQLite的操作

public class MyDatabaseAdapter {


 private static final String DB_NAME = "mzz.db";
 private static final String TABLE_NAME = "user";
 private static final String T_ID = "_id";
 private static final String T_USERNAME = "username";
 private static final String T_PASSWORD = "password";
 
 //数据库版本号
 private static final int VERSION = 1;
 
 private static final String CREATE_TABLE = "CREATE TABLE "
            + TABLE_NAME
            + " ( "
            + T_ID
            + " INTEGER PRIMARY KEY , "
            + T_USERNAME
            + " TEXT UNIQUE, "
            + T_PASSWORD
            + " TEXT )";
 
 private Context context = null ;
 private SQLiteDatabase sqliteDatabase = null ;
 private DatabaseHelper databaseHelper = null ;
 private static class DatabaseHelper extends SQLiteOpenHelper {
  
  DatabaseHelper(Context context) {
   super(context , DB_NAME , null, VERSION);
  }


  @Override
  public void onCreate(SQLiteDatabase db) {
   // TODO Auto-generated method stub
   db.execSQL(CREATE_TABLE);
  }


  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   // TODO Auto-generated method stub
   db.execSQL("DROP TABLE IF EXISTS notes");
   onCreate(db);
  }
 }
 
 //在创建对象的时候就返回一个sqliteDatabase
 public MyDatabaseAdapter(Context context) {
  this.context = context;
  try {
   open();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 //只有通过getWriteableDatabase才得到一个sqliteDatabase
 public void open() throws SQLException {
  databaseHelper = new DatabaseHelper(context);
  sqliteDatabase = databaseHelper.getWritableDatabase();
 }
 
 //插入数据,根据ID
 public long insertData(String username , String password) {
  ContentValues cv = new ContentValues();
  cv.put(T_USERNAME, username);
  cv.put(T_PASSWORD, password);
  return sqliteDatabase.insert(TABLE_NAME, T_ID, cv);
 }
 
 /**
 * 根据username和password查询数据,只有当两个数据同时存在一条数据时返回true,否则返回false
 * @param username
 * @param password
 * @return
 */
 public boolean queryByUnAndPw(String username , String password) {
  String sql = "select * from user where username='" + username +"' and password='" + password +"'";
  Cursor cur = sqliteDatabase.rawQuery(sql, null);
  if(cur != null) {
   if(cur.moveToNext()) {
    return true;
   } else {
    return false;
   }
  } else {
   return false;
  }
 }
 
 //查询表中的所有数据
 public Cursor queryAll() {
  return sqliteDatabase.query(TABLE_NAME, new String[]{T_ID,T_USERNAME,T_PASSWORD},
    null, null, null, null, null);
 }
}

相关推荐