如何使用类对象从db获取数据?

时间:2016-08-22 08:23:57

标签: android

我有一个用户类并成功在db中插入记录。现在我需要通过类对象获取所有这些记录。我是新手。任何人都可以告诉我如何才能实现这个目标?

import re
demo_dict = {}

with open("val.txt",'r') as f:
    for line in f:
          m= re.search(r"<<(.*?)>>(.*)",line)
          if m is not None:
               k = m.group(1)
               v = m.group(2).strip().split(',')
               if len(v) == 1:
                    v = v[0]
               demo_dict[k]=v
print demo_dict

2 个答案:

答案 0 :(得分:1)

在本教程中,我将举例说明如何在SQLite数据库中存储用户联系人。我使用名为Contacts的表来存储用户联系人。

http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

点击此链接

答案 1 :(得分:0)

首先,您必须创建一个具有相同getter和setter的类,因为您在数据库中有列,表示您正在创建类User.java,

public class User {
    //private variables
    int _id;
    String _name;
    String Password;
     int status
    // Empty constructor
    public User(){

    }
    // constructor
    public User(int id, String name, String Password,int status){
        this._id = id;
        this._name = name;
        this.Password = Password;
        this.status = status;
    }

    // constructor
    public User(String name, String Password){
        this._name = name;
        this.Password = Password;
        this.status = status;   
    }
    // getting ID
    public int getID(){
        return this._id;
    }

    // setting id
    public void setID(int id){
        this._id = id;
    }

    // getting name
    public String getName(){
        return this._name;
    }

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

    // getting pwd
    public String getPassword(){
        return this.Password;
    }

    // setting pwd
    public void setPassword(String status){
        this.Password = status;
    }

   // getting status
    public String getstatus(){
        return this.status;
    }

    // setting phone number
    public void setstatus(String status){
        this.Password = status;
    }
}

现在你需要使用数据库中的以下代码来获取数据库的所有记录,例如sqlite,

public List<User> getAllUser() {
            List<User> UserList = new ArrayList<User>();
            String selectQuery = "SELECT  * FROM " + TABLE_USER;


        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {

                User UserSingleUnit = new User();
                UserSingleUnit.setERId(c.getInt(c.getColumnIndex(KEY_ID)));
                UserSingleUnit.setName(c.getString(c.getColumnIndex(KEY_NAME)));
                UserSingleUnit.setPassword(c.getString(c.getColumnIndex(KEY_PWD)));
        UserSingleUnit.setStatus(c.getString(c.getColumnIndex(KEY_STATUS)));

                // add
                UserList.add(UserSingleUnit);
            } while (c.moveToNext());
        }
        // db.close();
        c.close();
        return UserList;
    }

它将最终解决您的问题