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

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

问题描述

我在Android上对我的SQLite数据库执行了一些查询。

I've executed some query on my SQLite db on Android.

主要使用的指令是:

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

现在,我想将此查询的结果转换为我在项目。如果你认为我想要一个ORM系统,你是对的,但我现在找到的是ORM系统,希望查询DB,保存对象在DB和管理数据库本身。
相反,我需要一个'简单'的ORM功能,可以做到正确的google.gson库使用JSON字符串,它转换JSON字符串到自定义对象,我想要相同,但转换SQLite游标到我的类

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. 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.

任何建议如何做?

推荐答案

't认为有一个自动化的方式来做到这一点。只需自己填充对象。例如,如果您的游标只是一个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.

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

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