【问题标题】:How to get column value from database using query?如何使用查询从数据库中获取列值?
【发布时间】:2012-04-09 19:01:10
【问题描述】:

我在使用带有 android 的 sqlite 数据库方面是全新的。 我想使用以下 SQL 语句从数据库中获取价值:

"SELECT description FROM games WHERE _id =" + categoryID

其中 categoryID 是被点击元素在 listView 中的位置(也是 _id 列的值)。

listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,

                String categoryID = new Integer(position).toString();

                final String SELECT_FROM = "SELECT description " + "FROM games "
                        + "WHERE _id = " + categoryID;
                database.query(SELECT_FROM);

                Intent intent = new Intent();
                intent.setClass(SqliteDbActivity.this, ViewAction.class);

                Bundle b = new Bundle();
                b.putString("categoryID", SELECT_FROM);
                intent.putExtras(b);

                startActivity(intent);

            }
        });

我知道我应该使用database.query()但是我应该如何正确编写前面的sql语句来获取值?

表格如下:

_id description name
1    some1       name1
2    some2       name2       
3    some3       name3    

请帮忙。

【问题讨论】:

  • 您的ListView 使用哪种Adapter
  • @MisterSquonk 我正在使用ArrayAdapter&lt;String&gt;

标签: android sql sqlite


【解决方案1】:
String categoryID = new Integer(position).toString();

            final String SELECT_FROM = "SELECT description " + "FROM games "
                    + "WHERE _id = " + categoryID;
            Cursor cursor = database.query(SELECT_FROM);
            cursor.moveToFirst();

            Intent intent = new Intent();
            intent.setClass(SqliteDbActivity.this, ViewAction.class);

            Bundle b = new Bundle();
            b.putString("categoryID", cursor.getString(cursor.getColumnIndex("fieldname"));
            intent.putExtras(b);

            startActivity(intent);

你的database.query(SELECT_FROM) 将返回cursor,在光标的帮助下你可以做你的工作

【讨论】:

  • Thaks,但我可以使用 bundle 将此值传递给下一个活动吗?
  • 好的,应该用什么来代替"fieldname"
  • 索引 0,1,2... 取决于表中的列数。 cursor.getString(0) 将返回第一列值。
  • 那么如果我在问题索引处有表格,那么索引将为 1?或者我误解了你。
  • 0 将是您的索引 cursor.getString(0),而不是 1
猜你喜欢
  • 2019-10-01
  • 2021-09-14
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多