2012-02-19 74 views
1

我想写一个查询从SQLite数据库中检索数据。我想在文本框中打印查询结果。所以我对光标使用了一个getint()方法。以下是我的代码。它不会在我的Android模拟器中启动。这是编写查询的正确方法吗?它没有显示任何错误。Sqlite数据库查询写作

import android.app.Activity; 
import android.os.Bundle; 
import android.app.Activity; 
import android.database.Cursor; 
import android.database.sqlite.*; 
import android.os.Bundle; 
import android.widget.TextView; 
import android.widget.Toast; 

public class SQLDemo1Activity extends Activity { 
    private SQLiteDatabase db; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    try{ 
     db= SQLiteDatabase.openDatabase(
     "/data/data/cis493.sqldatabases/databases/multilinguialdatabase.sqlite", 
     null, 
     SQLiteDatabase.CREATE_IF_NECESSARY); 
     db.beginTransaction(); 
     Cursor cursor = db.query(
     "colors" /* table */, 
     new String[] { "ID" } /* columns */, 
     "English = ?" /* where or selection */, 
     new String[] { "green" } /* selectionArgs i.e. value to replace ? */, 
     null /* groupBy */, 
     null /* having */, 
     null /* orderBy */ 
    ); 
     int id = cursor.getInt(0); 
     TextView met = (TextView) findViewById(R.id.t1); 
     met.setText(id); 
     db.endTransaction(); 
     db.close(); 
    } 
    catch(SQLiteException e) { 
     Toast.makeText(this, e.getMessage(), 1).show(); 
    } 
    } 
} 
+0

你会得到什么错误? – Snicolas 2012-02-19 09:32:28

+1

哦,顺便说一下,你的ide不需要你缩进你的代码。你的编译器也不需要它。但是程序员,可能是你或我们,需要它。 – Snicolas 2012-02-19 09:33:30

回答

1

在尝试使用getInt()获取int之前,需要先放置cursor.moveToNext()或cursor.moveToFirst()。将它放在if语句中,因为在游标中可能没有结果。

2

要写入Android中Sqllite查询需要特定的参数,如:

//查询用户字典并返回结果 mCursor = getContentResolver()的查询(

URI         // The content URI of the words table 
mProjection,      // The columns to return for each row 
mSelectionClause     // Selection criteria 
mSelectionArgs,      // Selection criteria 
mSortOrder);      // The sort order for the returned rows 

详情读机器人。开发人员的网站: http://developer.android.com/guide/topics/providers/content-provider-basics.html