2011-03-31 187 views
3

如何从数据库中获取信息。我想执行这一行从数据库sqlite中获取信息

String nom = db.execSQL("select name from person where id='+id+'"); 

任何一个可以纠正我此行从表人

+0

你应该张贴问题之前,有[搜索](http://stackoverflow.com/search?q=Using+Database+in+Android)StackOverflow上。 – Mudassir 2011-03-31 10:16:06

+0

这里id是int? – 2011-03-31 10:17:01

+0

尝试这一行db.execSQL(“select person from person where id ='”+ id +“'”); – 2011-03-31 10:49:05

回答

8

如果您的id是integer数据类型,请尝试此操作。

public String getResult(int id) 
{ 
    String name = null; 
    try 
    { 
     Cursor c = null; 
     c = db.rawQuery("select name from person where id="+id, null); 
     c.moveToFirst(); 
     name = c.getString(c.getColumnIndex("name")); 
     c.close(); 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
    return name; 
} 

皮斯试试这个,如果你的ID是字符串数据类型。

public String getResult(String id) 
{ 
    String name = null; 
    try 
    { 
     Cursor c = null; 
     c = db.rawQuery("select name from person where id=" + "\""+id+"\"", null); 
     c.moveToFirst(); 
     name = c.getString(c.getColumnIndex("name")); 
     c.close(); 
    } 
    catch(Exception e) 
    { 
     e.printStackTrace(); 
    } 
    return name; 
} 
+0

小提示:名称不是一个int :) – WarrenFaith 2011-03-31 10:29:24

+0

感谢warren它的我的错误... – 2011-03-31 10:30:50

+0

非常好,写得很好的答案,正是我所需要的。非常感谢。 – raddevus 2016-03-18 15:29:53

1
Cursor cursor = db.rawQuery("SELECT name FROM person WHERE id = ?", new String[] { id }); 
cursor.moveToFirst(); 
String nom = cursor.getString(cursor.getColumnIndex("name")); 

这应该是最简单的方法(未测试得到的人的名字,但你应该得到这个想法)。

它也看起来像你不知道android如何处理数据库访问,所以我建议看看至少在Cursor类。

execSQL()文件:

执行一个SQL语句不是SELECT或返回数据的任何其他SQL语句。