如何在Android上使用MyDbAdapter进行此查询?

时间:2011-01-22 18:28:33

标签: android sql sqlite

我有一个MyDBAdapter类,可以做一些简单的选择,但现在我需要一个特殊的选择。我需要实现这个选择:

SELECT * FROM position WHERE fk_email='given value by variable'

但我的android的dbadapter技能非常低......我不知道该怎么做。

我必须添加两个新方法:

public Cursor fetchPositionsByEmail(String fk_email)

public List<Position> retrievePositionsByEmail(String fk_email) 

我试过这些实现,但它们没有用,它们给我一个空位置:

public Cursor fetchPositionsByEmail(String email) throws SQLException {

    Cursor mCursor = mDb.query(true, "position", new String[] {"idposition", "latitude", "longitude", "timestamp", "fk_email"}
        , "fk_email" + "='" + email+"'", null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}

public List<Position> retrievePositionsByEmail(String email) 
{
 List <Position> positions=new ArrayList<Position>();
 Cursor result=fetchPositionsByEmail(email);
 if( result.moveToFirst() ){
        do{
         positions.add(new Position(result.getString(result.getColumnIndexOrThrow("idposition")),
           result.getString(result.getColumnIndexOrThrow("latitude")), 
           result.getString(result.getColumnIndexOrThrow("longitude")),
           result.getString(result.getColumnIndexOrThrow("timestamp")),
           result.getString(result.getColumnIndexOrThrow("fk_email"))));
        }while( result.moveToNext() );
    }
 return positions;
}

有人可以帮助我在这个MyDBAdapter类上实现这两个方法吗?

这是班级:

public class MyDbAdapter {

    private static final String TAG = "NotesDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    private static final String DATABASE_NAME = "gpslocdb";
    private static final String PERMISSION_TABLE_CREATE = "CREATE TABLE permission ( fk_email1 varchar, fk_email2 varchar, validated tinyint, hour1 time default '08:00:00', hour2 time default '20:00:00', date1 date, date2 date, weekend tinyint default '0', fk_type varchar, PRIMARY KEY  (fk_email1,fk_email2))";
    private static final String USER_TABLE_CREATE = "CREATE TABLE user ( email varchar, password varchar, fullName varchar, mobilePhone varchar, mobileOperatingSystem varchar, PRIMARY KEY  (email))";
    private static final String POSITION_TABLE_CREATE = "CREATE TABLE position (idposition bigint, latitude varchar, longitude varchar, timestamp datetime, fk_email varchar, PRIMARY KEY (idposition))";


    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

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

        @Override
        public void onCreate(SQLiteDatabase db) {
         db.execSQL("DROP TABLE IF EXISTS user");
            db.execSQL("DROP TABLE IF EXISTS permission");
            db.execSQL("DROP TABLE IF EXISTS position");
            db.execSQL(PERMISSION_TABLE_CREATE);
            db.execSQL(USER_TABLE_CREATE);
            db.execSQL(POSITION_TABLE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            //db.execSQL("DROP TABLE IF EXISTS user");
            //db.execSQL("DROP TABLE IF EXISTS permission");
            //onCreate(db);
        }

  @Override
  public void onOpen(SQLiteDatabase db) {
   super.onOpen(db);
            //onCreate(db);
  }
  public void clearDb(SQLiteDatabase db){
   db.execSQL("DROP TABLE IF EXISTS user");
            db.execSQL("DROP TABLE IF EXISTS permission");
            db.execSQL("DROP TABLE IF EXISTS position");
            onCreate(db);
  }
  public void deleteUser(SQLiteDatabase db, String email)
  {
   db.execSQL("DELETE FROM user Where email='"+email+"'");
  }
  public void deletePermission(SQLiteDatabase db, String email)
  {
   db.execSQL("DELETE FROM permission Where fk_email2='"+email+"'");
  }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     * 
     * @param ctx the Context within which to work
     */
    public MyDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public MyDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
     //clearDB();
        mDbHelper.close();
    }

    public long createUser(String email, String password, String fullName, String mobilePhone, String mobileOperatingSystem) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("email",email);
        initialValues.put("password",password);
        initialValues.put("fullName",fullName);
        initialValues.put("mobilePhone",mobilePhone);
        initialValues.put("mobileOperatingSystem",mobileOperatingSystem);
        return mDb.insert("user", null, initialValues);
    }
    public long createPermission(String email1, String email2, String validated, String hour1, String hour2,
   String date1, String date2, String weekend, String fk_type) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("fk_email1",email1);
        initialValues.put("fk_email2",email2);
        initialValues.put("validated",validated);
        initialValues.put("hour1",hour1);
        initialValues.put("hour2",hour2);
        initialValues.put("date1",date1);
        initialValues.put("date2",date2);
        initialValues.put("weekend",weekend);
        initialValues.put("fk_type",fk_type);
        return mDb.insert("permission", null, initialValues);
    }
    public long createPosition(String idposition, String latitude, String longitude, String timestamp, String fk_email) 
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("idposition",idposition);
        initialValues.put("latitude",latitude);
        initialValues.put("longitude",longitude);
        initialValues.put("timestamp",timestamp);
        initialValues.put("fk_email",fk_email);
        return mDb.insert("position", null, initialValues);
    }



    public void clearDB() {
     mDbHelper.clearDb(mDb);        
    }

    public Cursor fetchAllUsers() {

        return mDb.query("user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}, null, null, null, null, null);
    }
    public Cursor fetchAllPermissions() {

        return mDb.query("permission", new String[] {"fk_email1", "fk_email2", "validated", "hour1", "hour2", "date1", "date2", "weekend", "fk_type"}, null, null, null, null, null);
    }

    public Cursor fetchUser(String email) throws SQLException {

        Cursor mCursor = mDb.query(true, "user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}
            , "email" + "=" + email, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }

    public List<Friend> retrieveAllFriends() 
    {
     List <Friend> friends=new ArrayList<Friend>();
     Cursor result=fetchAllUsers();
     if( result.moveToFirst() ){
            do{
                friends.add(new Friend(result.getString(result.getColumnIndexOrThrow("email")),result.getString(result.getColumnIndexOrThrow("password")), result.getString(result.getColumnIndexOrThrow("fullName")),result.getString(result.getColumnIndexOrThrow("mobilePhone")),result.getString(result.getColumnIndexOrThrow("mobileOperatingSystem"))));
            }while( result.moveToNext() );
        }
     return friends;
    }
    public List<Permission> retrieveAllPermissions() 
    {
     List <Permission> permissions=new ArrayList<Permission>();
     Cursor result=fetchAllPermissions();
     if( result.moveToFirst() ){
            do{
             permissions.add(new Permission(result.getString(result.getColumnIndexOrThrow("fk_email1")),
               result.getString(result.getColumnIndexOrThrow("fk_email2")), 
               Integer.parseInt(result.getString(result.getColumnIndexOrThrow("validated"))),
               result.getString(result.getColumnIndexOrThrow("hour1")),
               result.getString(result.getColumnIndexOrThrow("hour2")),
               result.getString(result.getColumnIndexOrThrow("date1")),
               result.getString(result.getColumnIndexOrThrow("date2")),
               Integer.parseInt(result.getString(result.getColumnIndexOrThrow("weekend"))),
               result.getString(result.getColumnIndexOrThrow("fk_type"))));
            }while( result.moveToNext() );
        }
     return permissions;
    }

    public void deleteUser(String email) throws SQLException
    {
     mDbHelper.deleteUser(mDb, email);
    }
    public void deletePermission(String email) throws SQLException
    {
     mDbHelper.deletePermission(mDb, email);
    }

}

1 个答案:

答案 0 :(得分:1)

尝试使用占位符而不是连接值。

  Cursor mCursor = mDb.query(true, "position", new String[] {"idposition", "latitude", "longitude", "timestamp", "fk_email"}
        , "fk_email=?", new String[] { email } , null, null, null, null);

由于您通过串联传递电子邮件地址,因此问题可能来自@符号。

我发现this post关于sql中的@