【发布时间】: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?