将SQLite游标的结果转换为我的对象 [英] Convert results of SQLite Cursor to my object

查看:101
本文介绍了将SQLite游标的结果转换为我的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Android上的SQLite数据库上执行了一些查询.

I've executed some queries on my SQLite DB on Android.

使用的主要指令是:

Cursor cursor = myDB.rawQuery(select, null);

现在,我希望将此查询的结果转换为我在项目中创建的通用类.如果您认为我想要一个ORM系统,那是对的,但是我现在发现的只是想要查询数据库,将对象保存在数据库中以及管理数据库本身的ORM系统.

Now I want the results of this query to be converted to a generic class I've created in the project. If you think I want an ORM system, you are right, but all I've found now are ORM systems that want to query the DB, save objects in the DB and manage the DB itself.

现在,我需要一个简单"的ORM功能,该功能可以完全完成google.gson库对JSON字符串的处理,它将JSON字符串转换为自定义对象,我希望将其转换为将SQLite游标转换为我的类.

Instead now I need a 'simple' ORM feature that can do exactly what the google.gson library does with JSON strings, it converts JSON strings to custom objects, and I want the same but for converting SQLite cursors to my Classes.

任何建议如何做到这一点?

Any suggestion how to do this?

推荐答案

我认为没有自动的方法可以做到这一点.只需自己填充对象即可.例如,如果您的光标只是一个ID和一个名称,而您想创建一个Person对象:

I don't think there is an automated way to do this. Just populate the object yourself. For example, if your cursor was just an id and a name and you wanted to create a Person object:

Person populatePerson(Cursor cursor)
{
    try
    {
        int idIndex = cursor.getColumnIndexOrThrow("_id");
        int nameIndex = cursor.getColumnIndexOrThrow("name");
        long id = cursor.getLong(idIndex);
        String name = cursor.getString(nameIndex);
        return new Person(id, name);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

您可以将此函数包装在自己的Cursor类中,以使过程透明.

You could wrap this function in your own Cursor class to make the process transparent.

这篇关于将SQLite游标的结果转换为我的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆