2015-06-12 182 views
-7

我是一個非常沒有經驗的程序員,所以請原諒我,但我已經在網上搜索了很多,並且什麼都沒有提出。從SQLite數據庫中獲取價值:

我有一個Java程序,我在其中使用SQLite數據庫。我只需要獲取存儲在特定列和行中的值並將其轉換爲字符串變量。

有人可以請給我一個非常簡單和普遍的方式做到這一點?我想它是像「獲取名稱在ID = 4」的東西。

在此先感謝!

+0

網絡上有數百個教程。 –

+0

http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html – pcj

+1

你不應該要求一個現成的代碼,但應該做的教程。 –

回答

0

要得到你需要使用遊標或多個值,請參見下面的函數(即返回第一個值,它是完美的得到的id ,例如):

public String getSingular_Value_InTransaction(String query){ 
    //Declaration of variables 
    Cursor a1 = null; 

    try{ 
     a1 = database.rawQuery(query,null); 
     a1.moveToFirst(); 

     if(a1.getString(0) != null){ 
      String result = a1.getString(0); 
      a1.close(); 
      return result; 
     } 
     else{ 
      a1.close(); 
      return ""; 
     } 
    } 
    catch (NullPointerException ex){ 
     return ""; 
    } 
    catch (CursorIndexOutOfBoundsException ex){ 
     return ""; 
    } 
    catch (Exception ex){ 
     Log.e("-- BDD.execute_SelectCommand --","Exception", ex); 
     return ""; 
    } 
} 

告訴我,如果我幫你和好的編程!

0

使用這種方法,我想這會有所幫助...

public ArrayList<DbHelper> selectData() { 
     try { 
      Integer subCategoryArray[][] = null;  
      SQLiteDatabase db; 
      db = this.getReadableDatabase(); // Read Data 
       ArrayList<DbHelper> ar = new ArrayList<DbHelper>(); 
      String strSQL = "SELECT * FROM " + TABLE_NAME; 
      Cursor cursor = db.rawQuery(strSQL, null); 

       if(cursor != null) 
       { 
        if (cursor.moveToFirst()) { 
         subCategoryArray = new Integer[cursor.getCount()][cursor.getColumnCount()]; 

         int j= 0; 
         do {     
          subCategoryArray[j][0] = cursor.getInt(0); 
          subCategoryArray[j][1] = cursor.getInt(1); 
          subCategoryArray[j][2] = cursor.getInt(2); 
          subCategoryArray[j][3] = cursor.getInt(3); 
          subCategoryArray[j][4] = cursor.getInt(4); 
          subCategoryArray[j][5] = cursor.getInt(5); 
          subCategoryArray[j][6] = cursor.getInt(6); 
          subCategoryArray[j][7] = cursor.getInt(7); 
          subCategoryArray[j][8] = cursor.getInt(8); 
          subCategoryArray[j][9] = cursor.getInt(9); 
          subCategoryArray[j][10] = cursor.getInt(10); 
          subCategoryArray[j][11] = cursor.getInt(11); 
          subCategoryArray[j][12] = cursor.getInt(12); 


          DbHelper v= new DbHelper(subCategoryArray[j][0],subCategoryArray[j][1],subCategoryArray[j][2],subCategoryArray[j][3],subCategoryArray[j][4],subCategoryArray[j][5],subCategoryArray[j][6],subCategoryArray[j][7],subCategoryArray[j][8],subCategoryArray[j][9],subCategoryArray[j][10],subCategoryArray[j][11],subCategoryArray[j][12]); 
          ar.add(v); 
          j++; 
         } while (cursor.moveToNext());      

        } 
       } 
       cursor.close(); 

       return ar; 

     } catch (Exception e) { 
      return null; 
     } 

    }