从sql数据库一个细胞 [英] select one cell from sql database
问题描述
我想一个简单的SQL命令wihtin我的Android的应用程序,以获得选定人员的年龄:
I'm trying a simple SQL Command wihtin my Android-App, to get the age of a selected Person:
public int getAge(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name =? " + MainActivity.selectedPerson.getText().toString(), null);
int age = cursor.getInt(3); // column with ages
cursor.close();
db.close();
return age;
}
但是当我运行我的应用程序,它,当我调用函数getAge()崩溃。我收到以下错误:
But when I run my app, it crashes when I call the function getAge(). I get the following Error:
SQLiteException: no such column: Max: , while compiling: SELECT * FROM persons WHERE name = Max
我不明白这一点。有在表中的名称为最大。我究竟做错了什么?先谢谢了。
I don't get it. There is the name "Max" in the table. What am I doing wrong? Thanks in advance.
编辑2:
随着这一个:
Edit 2: With this one:
Cursor cursor = db.rawQuery("SELECT name FROM persons WHERE name = '" + MainActivity.selectedPerson.getText().toString() + "'", null);
我得到一个不同的错误:
I get a different error:
08-27 19:43:47.573: E/AndroidRuntime(6161): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
这是什么意思?
推荐答案
您应该考虑使用 rawQuery的)的
至prevent SQL注入攻击的: selectionArgs两个
参数(
You should consider using the selectionArgs
parameter of rawQuery()
to prevent SQL Injection Attacks:
Cursor cursor = db.rawQuery("SELECT * FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString() });
此外,你只需要的有一个的列,这样,而不是用 *
,你应该只选择一列中选择他们所有的资源浪费:
Also you only need one column so rather than wasting resources by selecting them all with *
, you should just select the one column:
Cursor cursor = db.rawQuery("SELECT age FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString() });
希望帮助!
总之它应该是这样的:
public int getAge(){
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT age FROM persons WHERE name = ?", new String[] { MainActivity.selectedPerson.getText().toString() });
int age;
// Check if you have a valid result and move to the first row to read it
if(cursor.moveToFirst())
age = cursor.getInt(0);
// Prevent a crash if there is no data for this name
else
age = 0;
cursor.close();
db.close();
return age;
}
这篇关于从sql数据库一个细胞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!