我想使用StringBuffer而不是将字符串与结果连接。我使用此代码转换while循环但我遇到了最后一个if语句的问题。我该怎么做才能转换它?
原始代码:
result = statement.executeQuery(sql);
String string = "";
while (result.next()) {
string += result.getString(("Hello") + ",");
}
if (string!= null && !string.isEmpty()) {
string= string.substring(0, string.length() - 1);
}
我的尝试:
result = statement.executeQuery(sql);
StringBuffer string = new StringBuffer("");
while (result.next()) {
string.append(("Hello") + ",")
}
if {
--- CODE HERE ---
}
任何帮助?
答案 0 :(得分:2)
如果您只想删除最后一个逗号,请尝试以下操作:
StringBuffer buffer = new StringBuffer("");
...
if ( buffer.length() > 0 ) {
buffer.deleteCharAt( buffer.length() - 1 );
}
答案 1 :(得分:1)
result = statement.executeQuery(sql);
StringBuffer buffer = new StringBuffer();
int length = result.size();
if(result != null && length > 0)
{
while (result.next()) {
buffer.append(result.getString(("Hello"));
if(--length > 0)
buffer.append(",");
}
}
答案 2 :(得分:0)
您可以使用if语句执行此操作。
result = statement.executeQuery(sql);
StringBuffer stringBuffer = new StringBuffer("");
while (result.next()) {
stringBuffer.append(("Hello") + ",")
}
if (stringBuffer.length()>0) {
stringBuffer = new StringBuffer(stringBuffer.substring(0, stringBuffer.length() - 1));
}