我正在开发一个多线程项目,其中我需要随机查找将在 SELECT sql
中使用的列
,然后我将执行该 SELECT sql询问。
找到这些列后-
- 我需要查看 id 是否在有效范围之间,如果在有效范围之间,则使用 columnsList 中的这些列循环结果集,并取回数据并将其存储在变量中。
- 否则,如果 id 不在有效范围内,我需要检查是否没有从结果集中获取任何数据。但不知何故,如果我取回数据并且标志为 true 来停止程序,则退出程序。否则,如果我正在取回数据,但标志为 false 以停止程序,则计算发生了多少次。
下面是我的代码-
private volatile int count;
@Override
public void run() {
.....
final String columnsList = getColumns(table.getColumns());
....
rs = preparedStatement.executeQuery();
....
if (Read.endValidRange < id && id < Read.startValidRange) {
while (rs.next()) {
for(String column: columnsList.split(",")) {
System.out.println(column + ": " + rs.getString(column));
}
}
} else {
if(rs.next() && Read.flagTerminate) {
System.exit(1);
} else {
count++;
}
}
....
}
/**
* A simple method to get the column names in the order in which it was
* inserted
*
* @param columns
* @return
*/
private String getColumns(final List<String> columns) {
List<String> copy = new ArrayList<String>(columns);
Collections.shuffle(copy);
int rNumber = random.nextInt(columns.size());
List<String> subList = copy.subList(0, rNumber);
Collections.sort(subList, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return columns.indexOf(o1) < columns.indexOf(o2) ? -1 : 1;
}
});
return StringUtils.join(subList, ",");
}
问题陈述-
我无法理解应该如何迭代结果集,因为每次我的 SELECT sql 中都会有不同的列,具体取决于生成的内容。除此之外,我怎样才能使其在 if else 循环中更加清晰。
最佳答案
好的..
您可以将随机生成的列保存在字符串数组中...然后在通过结果集迭代时使用该数组...如下所示:
更新
您不应在 select 语句中包含这些列。相反,您应该使用 *
选择 select 语句中的所有列...然后在 rs.next() 循环中获取该列的值...
rs = con.executeQuery("Select * from tablename");
while(rs.next())
{
for (String col : columnsList )
{
System.out.print(rs.get(col));
}
System.out.print("\n");
}
更新1
您需要将 run() 中编写的关键代码部分包装在同步块(synchronized block)中,以避免出现竞争条件,如下所示:
private volatile int count;
@Override
public void run() {
.....
while (!Read.flagTerminate)
{
synchronized(this)
{
if (!Read.flagTerminate)
{
String columnsList = getColumns(table.getColumns());
....
rs = preparedStatement.executeQuery();
....
if (Read.endValidRange < id && id < Read.startValidRange)
{
while (rs.next())
{
for(String column: columnsList.split(","))
{
System.out.println(column + ": " + rs.getString(column));
}
}
}
else
{
while (rs.next())
{
count++;
}
}
}
}
}
System.exit(0);//it implies that flag = true;
....
}
/**
* A simple method to get the column names in the order in which it was
* inserted
*
* @param columns
* @return
*/
private String getColumns(final List<String> columns) {
List<String> copy = new ArrayList<String>(columns);
Collections.shuffle(copy);
int rNumber = random.nextInt(columns.size());
List<String> subList = copy.subList(0, rNumber);
Collections.sort(subList, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return columns.indexOf(o1) < columns.indexOf(o2) ? -1 : 1;
}
});
return StringUtils.join(subList, ",");
}
关于java - 根据生成的列循环遍历结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15121008/