【问题标题】:Creating a table in Android在 Android 中创建表
【发布时间】:2012-12-05 17:21:37
【问题描述】:

我的第一篇文章。我是第一次涉足 Android 开发,Java 编程经验有限。关于我的问题...

在 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);"
);

我已经看到了这两种方式,我试图理解为什么更多的代码会比更少的代码更好。

谢谢!

【问题讨论】:

  • 最好的方法是将所有final/constants 存储在一个单独的类中。所以在future如果有什么需要改变的,那么你可以很容易地在一堂课中改变。

标签: android coding-style create-table


【解决方案1】:

@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);
}

【讨论】:

    【解决方案2】:

    作为最佳实践,您应该使用常量来创建。这将在您以后想要对表格进行一些更改时为您提供帮助

    【讨论】:

      【解决方案3】:

      我个人更喜欢将它们保存在最终的静态字符串变量中,这样我就可以在一个地方轻松地编辑它们,这样我就更容易阅读它并更改可能适用于多个数据库的内容。我认为这是大多数开发人员最喜欢的方式。

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

      您可以非常轻松地访问它们

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

      【讨论】:

      • 我喜欢这个主意。不过,似乎仍然比必要的代码多一些。谢谢!
      • 是的,但您总能找到变通方法来减小代码大小!
      猜你喜欢
      • 2011-06-28
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-26
      • 2014-11-22
      相关资源
      最近更新 更多