如何将运行时值作为存储在属性文件中的sql查询中的变量传递

时间:2016-08-09 07:47:20

标签: java mysql

我参与了数据库应用程序的框架开发,我将各种sql查询存储在属性文件中。这些查询存储在属性文件中,其中id值为变量,即

#query1 which finds deductible value
deductiblevalue=Select deductible from TableName Where planId='V_PLAN_ID';

其中V_PLAN_ID是查询中的变量。

当我从属性文件中调用V_PLAN_ID查询并在db上运行查询时,应在运行时定义

deductiblevalue

1 个答案:

答案 0 :(得分:0)

您可以使用PreparedStatement

首先,用问号替换变量,这些是基于索引的查询变量:

deductiblevalue=SELECT `deductible` FROM `TableName` WHERE planId = ?;

接下来,导入属性文件并将String读入PreparedStatement

final Properties queries = //read somehow
try(final Connection connection = dataSource.getConnection();
    final PreparedStatement statement = connection.prepareStatement(queries.getProperty("deductiblevalue"))) {
}

现在,设置变量的值 - 这些是1 - indexed和typesafe:

statement.setInt(vPlanId);

正常执行

try(final ResultSet resultSet = statement.executeQuery()) {
    //read results
}