【问题标题】:SQLite query statements in separate file单独文件中的 SQLite 查询语句
【发布时间】:2016-10-31 16:28:15
【问题描述】:

我正在开发一个 Android 应用程序,我想将我的 SQLite 查询语句保留在我的 Java 类之外。

我考虑使用 .properties 文件来存储我的所有 SQL 语句。听起来不错,.properties 文件中的每个属性都包含一个字符串 - 我什至可以存储准备好的语句并为它们提供所需的参数,例如:

get.student.with.first.name=SELECT * FROM Students WHERE FirstName = ?;

但是,我也为我的数据库表实现了持久性合同,如下所示:

public final class StudentPersistenceContract {
    private StudentPersistenceContract() {}

    public static abstract class StudentEntry implements BaseColumns {
        public static final String TABLE_NAME = "Student";

        public static final String COLUMN_FIRST_NAME = "FirstName";
        public static final String COLUMN_LAST_NAME = "LastName";
    }
}

我不想将表名和列名硬编码到 .properties 文件的条目中,我想像这样动态访问它们:StudentPersistenceContract.StudentEntry.TABLE_NAME 等。

我想到的一件事是创建一个无法实例化的类来“构造”我需要的查询。类似的东西......

public final class SqlQueryConstructor {

    private SqlQueryConstructor() {}

    public static final String GET_STUDENT_WITH_FIRST_NAME = "SELECT * FROM " + StudentPersistenceContract.StudentEntry.TABLE_NAME + " WHERE " + StudentPersistenceContract.StudentEntry.COLUMN_FIRST_NAME + " = ?;";
}

这样我可以通过访问获得所需的 SQL 查询:SqlQueryConstructor.GET_STUDENT_WITH_FIRST_NAME

这仍然是一个 Java 类,但很高兴知道我的所有 SQL 都在那里,而不是分散在各处。

这是个好主意吗?还有其他选择吗?

【问题讨论】:

  • I considered using a .properties file, in which to store all of my SQL statements. Sounds fine, each property in a .properties file holds a string 为什么不使用 strings.xml

标签: java android sql sqlite


【解决方案1】:

我决定使用我的第二种方法 - 为 SQLite 语句使用带有静态字段的类。我读到了何时使用 strings.xml 以及何时使用静态最终字符串:android - strings.xml vs static constantsAndroid strings, Should I use strings.xml or java strings 等。

所以我将使用 strings.xml 进行本地化,使用带有静态字段的类作为 SQL 语句。

【讨论】:

    猜你喜欢
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 2011-03-13
    • 2011-10-19
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    相关资源
    最近更新 更多