我想从数据库中获取数据

时间:2017-09-09 19:34:40

标签: android sqlite sqliteopenhelper

我想使用存储在我们的表事件中的游标来获取数据 但我无法获取该数据。 我怎么能这样做,请给我合适而简单的答案。

这是我的Database类,我在其中创建了数据库表表示和方法来对它们执行操作。

public class DatabaseHelper extends SQLiteOpenHelper
{
    private static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "students.db";
    public static final String Table_Name = "STUDENTINFO";

    public databaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
    {
       super(context, DATABASE_NAME, factory, DATABASE_VERSION);
       SQLiteDatabase DB = this.getWritableDatabase();
    }

    public void onCreate(SQLiteDatabase db)
    {
       String Query = "CREATE TABLE " + Table_Name + "( id INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, CONTACT TEXT, EMAIL TEXT );";
       db.execSQL(Query);
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        db.execSQL("DROP TABLE IF EXIST" + Table_Name);
        onCreate(db);
    }

}

2 个答案:

答案 0 :(得分:1)

从上面的代码中,您似乎没有数据库中的任何数据,只有一个空表。要启用数据添加,您可以将以下方法添加到Databasehelper类。

public void insertRow(String name, String contact, String email) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues cv = new ContentValues();
    cv.put("NAME",name);
    cv.put("CONTACT",contact);
    cv.put("EMAIL",email);
    db.insert(Table_Name,null,cv);
}

要从表中获取所有行,请将以下方法添加到DatabaseHelper类: -

public Cursor getAllRows() {
    SQLiteDatabase db = this.getWritableDatabase();

    return db.query(Table_Name,null,null,null,null,null,null);
}

要添加一些数据,您可以在活动中使用以下内容(可能称为MainActivity,这可以采用onCreate方法)

    int anyoldvalue_asnotused_justpasseed = -12345;
    // Note can't use DatabaseHelper.DATABASE_VERSION as it's private.
    DatbaseHelper dbhlpr = new DatabaseHelper(this,
        DatabaseHelper.DATABASE_NAME,
        null,
        anyoldvalue_asnotused_justpasseed);

    dbhlpr.insertRow("Fred","whatever","Fred@nowhere.com");
    dbhlpr.insertRow("Bert","more whatever","Bert@noemail.com");
    // mimic the above to add more data

注意!这将在每次启动App时添加两行。您通常会在允许输入数据然后提交数据的活动中模仿上述内容。

要获取数据,您可以使用以下内容(显然在添加数据后): -

    // Now access that data using the getAllRows instance method
    // which returns a Cursor named csr
    Cursor csr = dbhlpr.getAllRows();
    // Traverse the Cursor outputting all columns to the Log
    while (csr.moveToNext()) {
        Log.d("MYDATA",
                "Name is " + csr.getString(csr.getColumnIndex("NAME")) +
                        " Contact info is " + 
                        csr.getString(csr.getColumnIndex("CONTACT")) +
                        " Email is " +
                        csr.getString(csr.getColumnIndex("EMAIL")) +
                        " id is " +
                        Long.toString(csr.getLong(csr.getColumnIndex("id"))));
    }

这会将数据输出到日志,例如: -

09-10 12:51:14.075 4170-4170/? D/MYDATA: Name is Fred Contact info is whatever Email is Fred@nowhere.com id is 1
09-10 12:51:14.075 4170-4170/? D/MYDATA: Name is Bert Contact info is more whatever Email is Bert@noemail.com id is 2

但是我会建议一些人做些改变。

1)将DatabaseHelper类中的DatbaseHelper构造函数更改为仅需要传递的内容(即上下文),以便更改: -

    public databaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)
    {
       super(context, DATABASE_NAME, factory, DATABASE_VERSION);
       SQLiteDatabase DB = this.getWritableDatabase();
    }

    public databaseHelper(Context context)
    {
       super(context, DATABASE_NAME, null, DATABASE_VERSION);
       SQLiteDatabase DB = this.getWritableDatabase();
    }

并从

更改MainActivity中的以下内容
DatbaseHelper dbhlpr = new DatabaseHelper(this,
    DatabaseHelper.DATABASE_NAME,
    null,
    anyoldvalue_asnotused_justpasseed);

DatbaseHelper dbhlpr = new DatabaseHelper(this);

2)删除关键字 AUTOINCREMENT ,没有必要这样做,因为INTEGER PRIMARY KEY将导致增量唯一ID。请参阅此处以获取解释SQLite Autoincrement

3)由于使用列名访问列被认为是更好的做法,因此最好将列名更改为定义为DatabaseHelper类变量,如DATABASE_NAME和Table_Name已定义。这样做时,请使用 _id 而不是ID。 原因是如果你对ListViews和Spinners使用CursorAdapters,那么适配器需要一个名为_id的列,它应该是唯一的id。所以现在采用这个可能会在将来节省一些麻烦

以上是完成上述更改后的完整代码。

注意您应该在重新运行APP之前取消暂存应用程序或清除APP数据(或者onUpgrade调用onCreate,您可以增加数据库版本号)

原因是列 id 将更改为 _id (并且还删除了AUTOCOMPLETE)并且 onCreate 方法仅在没有数据库存在时自动运行,即 onCreate 每次启动应用程序时都不运行(除非根据代码强制执行此操作)。

所以这里改变了代码: -

DatabaseHelper.java: -

public class DatabaseHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "students.db";
    public static final String TABLENAME = "STUDENTINFO";
    public static final String IDCOLUMNNAME = "_id";
    public static final String NAMECOLUMNNAME = "NAME";
    public static final String CONTACTCOLUMNNAME = "CONTACT";
    public static final String EMAILCOLUMNNAME = "EMAIL";

    public DatabaseHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        SQLiteDatabase DB = this.getWritableDatabase();
    }

    public void onCreate(SQLiteDatabase db)
    {
        String Query = "CREATE TABLE " + TABLENAME + "(" +
                IDCOLUMNNAME + " INTEGER PRIMARY KEY," +
                NAMECOLUMNNAME + " TEXT," +
                CONTACTCOLUMNNAME + " TEXT," +
                EMAILCOLUMNNAME + " TEXT " +
                ");";
        db.execSQL(Query);
    }

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        db.execSQL("DROP TABLE IF EXIST " + TABLENAME);
        onCreate(db);
    }

    public void insertRow(String name, String contact, String email) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues cv = new ContentValues();
        cv.put(NAMECOLUMNNAME,name);
        cv.put(CONTACTCOLUMNNAME,contact);
        cv.put(EMAILCOLUMNNAME,email);
        db.insert(TABLENAME,null,cv);
    }

    public Cursor getAllRows() {
        SQLiteDatabase db = this.getWritableDatabase();

        return db.query(TABLENAME,null,null,null,null,null,null);
    }
}

MainActivity.java(如果这是您活动的名称): -

    // Get and instance of the DatbaseHelper class named dbhlpr
    DatabaseHelper dbhlpr = new DatabaseHelper(this);

    // Call the instances inertRow method to add some data
    dbhlpr.insertRow("Fred","whatever","Fred@nowhere.com");
    dbhlpr.insertRow("Bert","more whatever","Bert@noemail.com");

    // Now access that data using the getAllRows instance method
    // which returns a Cursor named csr
    Cursor csr = dbhlpr.getAllRows();
    // Traverse the Cursor outputting all columns to the Log
    while (csr.moveToNext()) {
        Log.d("MYDATA",
                "Name is " + csr.getString(csr.getColumnIndex(DatabaseHelper.NAMECOLUMNNAME)) +
                        " Contact info is " +
                        csr.getString(csr.getColumnIndex(DatabaseHelper.CONTACTCOLUMNNAME)) +
                        " Email is " +
                        csr.getString(csr.getColumnIndex(DatabaseHelper.EMAILCOLUMNNAME)) +
                        " id is " +
                        Long.toString(csr.getLong(csr.getColumnIndex(DatabaseHelper.IDCOLUMNNAME))));
    }
}

答案 1 :(得分:0)

最简单的答案:首先学习最佳实践,花一天时间学习如何正确编写和使用SQLite有很长的路要走:

https://www.udacity.com/course/android-basics-data-storage--ud845

最简单的答案:使用原理图注释库

https://github.com/SimonVT/schematic

最短的答案:祝你有愉快的一天。