如何从sqlite中检索数据

how to retrieve data from sqlite

我想加载用户创建帐户时的数据,我不确定该怎么做

在我想从帐户加载信息的 class 中,计划是显示并可能还更新用户提供的任何信息

有人可以帮我吗?

数据库助手


package com.example.tulio.appkolev.sql;


public class DatabaseHelper  extends SQLiteOpenHelper{

    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_NAME = "UserManager.db";

    private static final String TABLE_USER = "user";

    private static final String COLUMN_USER_ID = "user_id";
    private static final String COLUMN_USER_NAME = "user_name";
    private static final String COLUMN_USER_EMAIL = "user_email";
    private static final String COLUMN_USER_PASSWORD = "user_password";

    private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
            + COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_USER_NAME + " TEXT,"
            + COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" + ")";

    private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;

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

    @Override
    public void onCreate(SQLiteDatabase db){
        db.execSQL(CREATE_USER_TABLE);
    }

    @Override
    public  void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
        db.execSQL(DROP_USER_TABLE);
        onCreate(db);
    }

    public void addUser(User user){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_NAME, user.getName());
        values.put(COLUMN_USER_EMAIL, user.getEmail());
        values.put(COLUMN_USER_PASSWORD, user.getPassword());

        db.insert(TABLE_USER, null, values);
        db.close();
    }

    public boolean checkUser(String email){
        String[] columns = {
                COLUMN_USER_ID
        };
        SQLiteDatabase db = this.getWritableDatabase();
        String selection = COLUMN_USER_EMAIL + " = ?";
        String[] selectionArgs = { email };

        Cursor cursor = db.query(TABLE_USER,
                columns,
                selection,
                selectionArgs,
                null,
                null,
                null);
        int cursorCount = cursor.getCount();
        cursor.close();
        db.close();

        if (cursorCount > 0){
            return true;
        }
        return false;
    }

    public boolean checkUser(String email, String password){
        String[] columns = {
                COLUMN_USER_ID
        };
        SQLiteDatabase db = this.getWritableDatabase();
        String selection = COLUMN_USER_EMAIL + " = ?" + " AND " + COLUMN_USER_PASSWORD + " =?";
        String[] selectionArgs = { email, password };

        Cursor cursor = db.query(TABLE_USER,
                columns,
                selection,
                selectionArgs,
                null,
                null,
                null);
        int cursorCount = cursor.getCount();
        cursor.close();
        db.close();

        if (cursorCount > 0){
            return true;
        }
        return false;
    }
}

感谢您的帮助,如果有人可以向我解释如何将数据库从本地更改为在线,我将不胜感激

因为你有一个 User class 那么你可以提取所有数据和 return 一个 User。

您显然需要确定要 returned 并稍后更新的用户。通常,您会将 id 列作为 long 存储在用户 class 中,尽管这可能不是必需的,尽管其他列的 none 已定义使用 id 列的 UNIQUE 约束是避免任何歧义的正确方法。

因此,如果您还没有为 id 定义 class 的成员,那么建议您这样做,例如User class 可能是(该示例还使用了额外的构造函数):-

User.java

public class User {

    private long id;
    private String name;
    private String email;
    private String password;

    public User() {
    }

    public User(String name, String email, String password) {
        this(-1,name,email,password);
    }

    public User(long id, String name, String email, String password) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.password = password;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Databasehelper.java(其他方法)

DatabaseHelper class 可以有多种方法来提取用户对象,例如:-

public User getUserByID(long id) {
    User rv = new User();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.query(TABLE_USER,null,COLUMN_USER_ID + "=?",new String[]{String.valueOf(id)},null,null,null);
    if (cursor.moveToFirst()) {
        rv.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_USER_ID))); //<<<<<<<<<<optional
        rv.setName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
        rv.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
        rv.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
    }
    cursor.close();
    db.close();
    return rv;
}

public User getUserByName(String name) {
    User rv = new User();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.query(TABLE_USER,null,COLUMN_USER_NAME + "=?",new String[]{name},null,null,null);
    if (cursor.moveToFirst()) {
        rv.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_USER_ID))); //<<<<<<<<<<optional
        rv.setName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
        rv.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
        rv.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
    }
    cursor.close();
    db.close();
    return rv;
}
public User getUserByEmail(String email) {
    User rv = new User();
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.query(TABLE_USER,null,COLUMN_USER_EMAIL + "=?",new String[]{email},null,null,null);
    if (cursor.moveToFirst()) {
        rv.setId(cursor.getLong(cursor.getColumnIndex(COLUMN_USER_ID))); //<<<<<<<<<<optional
        rv.setName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
        rv.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
        rv.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
    }
    cursor.close();
    db.close();
    return rv;
}
  • 请注意,getUserById 是更可取的方法,因为不会出现歧义。

由于 id 绝对没有歧义你不妨 re-consider checkUser 这样它不仅检查用户但也 returns 已检查用户的 id。因此,还添加了此方法:-

public long checkUserGettingId(String email, String password) {
    long rv = -1;
    String[] columns = {
            COLUMN_USER_ID
    };
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.query(TABLE_USER,columns,COLUMN_USER_EMAIL + "=? AND " + COLUMN_USER_PASSWORD + "=?",new String[]{email,password},null,null, null);
    if (cursor.moveToFirst()) {
        rv = cursor.getLong(cursor.getColumnIndex(COLUMN_USER_ID));
    }
    cursor.close();
    db.close();
    return rv;
}

最后,您可以使用以下方法进行更新,这些方法都基于更新用户对象:-

public int updateUserByID(User user, long id) {
    int rv = 0;
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(COLUMN_USER_NAME,user.getName());
    cv.put(COLUMN_USER_EMAIL,user.getEmail());
    cv.put(COLUMN_USER_PASSWORD,user.getPassword());
    rv = db.update(TABLE_USER,cv,COLUMN_USER_ID + "=?",new String[]{String.valueOf(id)});
    db.close();
    return rv;
}
public int updateUser(User user) {
    return updateUserByID(user, user.getId());
}

- the subtle difference being that the first, as it uses an independent **id** could be a little more flexible.

用法示例

以下是使用上述许多方法的代码(在本例中为 Activity)。

  1. 最初添加 2 个用户。
  2. 然后使用 checkUserGettingID 方法有效登录。
  3. 通过 getUserById 方法提取用户数据,以获取登录用户的数据作为用户对象 (mCurrentUser)。
  4. 将用户数据输出到日志。
  5. 更新用户数据并再次检索记录更改数据的数据。
  6. 通过 getUserByEMail 方法提取用户数据(更新)并将数据输出到日志。
  7. 通过 getUserByName 方法提取用户数据(更新)并将数据输出到日志。
  8. 通过getUserByEmail方法提取第二个用户数据并输出到日志。
  9. 通过 getUserByEmail** 方法提取 non-existent 用户的数据并输出数据(所有值为空,除了 id 为 0(不是自动生成的id 因为第一个将是 1)) 到日志。请注意,您通常会通过检查有效 ID 和/或空值来检查用户是否存在。

使用的代码是:-

public class MainActivity extends AppCompatActivity {

    DatabaseHelper mDBHlpr;
    User mCurrentUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDBHlpr = new DatabaseHelper(this);

        //Add 2 Users
        mDBHlpr.addUser(new User("Fred","Fred@fredmail.com","password"));
        mDBHlpr.addUser(new User("Alice","Alice@alicemail.com","1234567890"));

        long userid = mDBHlpr.checkUserGettingId("Fred@fredmail.com","password");
        if (userid > 0) {
            mCurrentUser = mDBHlpr.getUserByID(userid); //<<<<<<<<<<< Get all the user info
            logUserInfo(mCurrentUser);

            //Update the user
            mCurrentUser.setName("Bert");
            mCurrentUser.setEmail("Bert@Bertmail.com");
            mCurrentUser.setPassword("anewpassword");
            mDBHlpr.updateUser(mCurrentUser);
            mCurrentUser = mDBHlpr.getUserByID(mCurrentUser.getId());
            logUserInfo(mCurrentUser);

            // Update the user again
            mCurrentUser.setName("Mary");
            mCurrentUser.setEmail("Mary@marymail.com");
            mCurrentUser.setPassword("mypasswordismary");
            mDBHlpr.updateUserByID(mCurrentUser,userid);
            // get by email
            mCurrentUser = mDBHlpr.getUserByEmail("Mary@marymail.com");
            logUserInfo(mCurrentUser);
            // get by Name
            mCurrentUser = mDBHlpr.getUserByName("Mary");
            logUserInfo(mCurrentUser);

            // get 2nd user
            mCurrentUser = mDBHlpr.getUserByEmail("Alice@alicemail.com");
            logUserInfo(mCurrentUser);

            //Oooops
            mCurrentUser = mDBHlpr.getUserByEmail("nobody@nobody@email.com");
            logUserInfo(mCurrentUser);
         }
    }

    private void logUserInfo(User user) {
        Log.d("USERINFO",
                "User ID is " + String.valueOf(user.getId()) +
                        " UserName = " + user.getName() +
                        " UserEmail = " + user.getEmail() +
                        " UserPassword = " + user.getPassword());
    }
}

结果

上面第一次运行时(代码设计成one-off运行)输出:-

06-26 10:02:26.795 12054-12054/? D/USERINFO: User ID is 1 UserName = Fred UserEmail = Fred@fredmail.com UserPassword = password
06-26 10:02:26.801 12054-12054/? D/USERINFO: User ID is 1 UserName = Bert UserEmail = Bert@Bertmail.com UserPassword = anewpassword
06-26 10:02:26.807 12054-12054/? D/USERINFO: User ID is 1 UserName = Mary UserEmail = Mary@marymail.com UserPassword = mypasswordismary
06-26 10:02:26.808 12054-12054/? D/USERINFO: User ID is 1 UserName = Mary UserEmail = Mary@marymail.com UserPassword = mypasswordismary
06-26 10:02:26.811 12054-12054/? D/USERINFO: User ID is 2 UserName = Alice UserEmail = Alice@alicemail.com UserPassword = 1234567890
06-26 10:02:26.812 12054-12054/? D/USERINFO: User ID is 0 UserName = null UserEmail = null UserPassword = null