方法EXCUTE查询并返回结果 [英] Method to excute query and return results

查看:151
本文介绍了方法EXCUTE查询并返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应用程序将无法运行 - 试图执行查询,打印某些值

方法:

 公开光标尝试(字符串VG){
    串Q =SELECT数量从+ TABLE_CONTACTS +,其中name =+ VG;
    SQLiteDatabase DB = this.getReadableDatabase();
    光标光标= db.rawQuery(Q,空);

            如果(光标!= NULL){
                cursor.moveToFirst();
            }
            返回游标;
    }
 

这是主要的调用方法

 光标哇= db.trying(金);
文=(TextView的)findViewById(R.id.textView13);
text.setText((CharSequence中)(WOW));
 

解决方案

在第一。既然你是直接添加艰难变量into语句,变量必须包裹以单引号或者它interpeted作为列。

 选择购买数量从+ TABLE_CONTACTS +,其中name ='+ V​​G +';
 

和第二个大的问题,看看这里:

  text.setText((CharSequence中)(WOW));
 

在这里,您试图投光标的CharSequence ,但是这是不可能的。如果你想从游标检索数据,你必须使用一个从游标类的干将方法在您的案件的getString()方式:

 字符串数量= wow.getString(0); //返回从游标的数量
text.setText(数量);
 

现在它应该工作。

建议:

我建议你的使用的参数化的语句的,实际上使用占位符在查询中。他们从数据库中添加和检索数据/提供更多更安全的方式。

让我们来重写你的code:

 串Q =SELECT数量从+ TABLE_CONTACTS +,其中name =?;
SQLiteDatabase DB = this.getReadableDatabase();
光标光标= db.rawQuery(Q,新的String [] {VG});
 

它的工作原理简单。占位符 将被替换为您的字符串值。

App won't run - trying to execute query to print certain value

Method:

public Cursor trying(String vg){
    String q="SELECT quantity FROM " + TABLE_CONTACTS +  " WHERE name=" + vg;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor  cursor = db.rawQuery(q,null);

            if (cursor != null) {
                cursor.moveToFirst();
            }
            return cursor;
    }

Calling method from main

Cursor wow = db.trying("gold");
text = (TextView) findViewById(R.id.textView13);
text.setText((CharSequence) (wow));

解决方案

At first. Since you are directly adding trying variables into statement, variable must be wrapped to single quotes or it's interpeted as column.

"SELECT quantity FROM " + TABLE_CONTACTS +  " WHERE name= '" + vg + "'";

And second "big" problem, look here:

text.setText((CharSequence) (wow));

Here you are trying to cast Cursor to CharSequence but it's not possible. If you want to retrieve data from Cursor you have to use one from the getters methods of Cursor class in your case getString() method:

String quantity = wow.getString(0); // it returns your quantity from Cursor
text.setText(quantity);

Now it should works.

Recommendation:

I suggest you to an usage of parametrized statements which actually use placeholders in your queries. They provide much more safer way for adding and retrieving data to / from database.

Let's rewrite your code:

String q = "SELECT quantity FROM " + TABLE_CONTACTS + " WHERE name = ?";
SQLiteDatabase db = this.getReadableDatabase();
Cursor  cursor = db.rawQuery(q, new String[] {vg});

It works simply. Placeholder ? will be replaced with your string value.

这篇关于方法EXCUTE查询并返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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