方法EXCUTE查询并返回结果结果、方法、EXCUTE

由网友(红薇染露)分享简介:应用程序将无法运行 - 试图执行查询,打印某些值方法:公开光标尝试(字符串VG){串Q =SELECT数量从+ TABLE_CONTACTS +,其中name =+ VG;SQLiteDatabase DB = this.getReadableDatabase();光标光标= db.rawQuery(Q,空);如果(光...

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

方法:

 公开光标尝试(字符串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));
 
Excel 查找内容出现次数 并返回每次出现的行号

解决方案

在第一。既然你是直接添加艰难变量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.

阅读全文

相关推荐

最新文章