2012-12-05 112 views
0

對我而言,這是第一篇文章。我第一次涉足Android開發,只有有限的Java編程經驗。在我的問題...在Android中創建表格

當在dbHelper類中創建多個表時,哪種方法是首選?

初始化變量來保存創建的字符串...

private static final String DATABASE_CREATE = 
      "create table notes (_id integer primary key autoincrement, "+ 
      "title text not null, body text not null);"; 

db.execSQL(DATABASE_CREATE); 

或只是......

db.execSQL("create table notes (_id integer primary key autoincrement, "+ 
      "title text not null, body text not null);" 
); 

我已經看到了這兩種方式,我試圖理解爲什麼越來越多的代碼會更好。

謝謝!

+1

最好的方法訪問它們將存儲所有'終/ constants'在一個單獨的類。所以在將來'如果有什麼事情需要改變,那麼你可以在一個班級輕鬆改變。 –

回答

0

@MrCleanX這樣做。

public class DatabaseHandler extends SQLiteOpenHelper { 

// All Static variables 
// Database Version 
private static final int DATABASE_VERSION = 1; 

// Database Name 
private static final String DATABASE_NAME = "contactsManager"; 

// Contacts table name 
private static final String TABLE_CONTACTS = "contacts"; 

// Contacts Table Columns names 
private static final String KEY_ID = "id"; 
private static final String KEY_NAME = "name"; 
private static final String KEY_PH_NO = "phone_number"; 

public DatabaseHandler(Context context) { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
} 

// Creating Tables 
@Override 
public void onCreate(SQLiteDatabase db) { 
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "(" 
      + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT," 
      + KEY_PH_NO + " TEXT" + ")"; 
    db.execSQL(CREATE_CONTACTS_TABLE); 
} 

// Upgrading database 
@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    // Drop older table if existed 
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS); 

    // Create tables again 
    onCreate(db); 
} 
0

作爲一種最佳實踐,您應該使用常量創建。這會幫助你,當你想稍後做一些改變時

0

我個人更喜歡把它們保存在最終的靜態字符串變量中,這樣我就可以在一個地方輕鬆地編輯它們,這樣我會更容易閱讀它會改變可能適用於多個數據庫的內容。我認爲這是大多數開發人員最喜歡的方式。

public class myVariables { 
    public final static String firstTable = "firstTableCreationQuery"; 
    public final static String secondTable = "secondTableCreationQuery"; 
} 

而且你可以很容易

... 
db.execSQL(myVariables.firstTable); 
db.execSQL(myVariables.secondTable); 
... 
+0

我喜歡這個想法。儘管如此,仍然看起來有點多的代碼。謝謝! – MrCleanX

+0

是的,但認爲你總是可以找到解決方法來減少代碼的大小! – Pavlos