我有一个方法' getAllIDs(),用于获取数据库中特定表的ID。我的项目中有许多方法使用它。
public static int[] getAllIDs (String TableName, String WhereClause, String trxName)
{
ArrayList<Integer> list = new ArrayList<Integer>();
StringBuffer sql = new StringBuffer("SELECT ");
sql.append(TableName).append("_ID FROM ").append(TableName);
if (WhereClause != null && WhereClause.length() > 0)
sql.append(" WHERE ").append(WhereClause);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql.toString(), trxName);
rs = pstmt.executeQuery();
while (rs.next())
list.add(new Integer(rs.getInt(1)));
}
}
Run Code Online (Sandbox Code Playgroud)
其中子句是查询的条件部分。由于有此条款,因此有机会进行sql注入。因此,我需要修改此方法以使用准备好的语句参数设置来设置参数。我面临的问题是因为' getAllIDs()'不知道每个子句有多少个参数。
每个子句的参数都不同,可以是任意数字。对于某些类,参数将为3,对于某些类,参数将为2,依此类推,具有不同的数据类型。因此,我该如何使用setstring(),setint()等。用我发布的代码向我解释。
将附加PreparedStatementBinder参数传递给方法:
public interface PreparedStatementBinder {
/**
* Binds all the arguments to the given prepared statement
*/
public void bindArguments(PreparedStatement statement) throws SQLException;
}
Run Code Online (Sandbox Code Playgroud)
调用者将必须传递where子句(例如"foo = ? and bar = ?")和该接口的实例,例如
new PreparedStatementBinder() {
@Override
public void bindArguments(PreparedStatement statement) throws SQLException {
statement.setString(1, theFoo);
statement.setInt(2, theBar);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1825 次 |
| 最近记录: |