private void tree(Connection conn, int id, int level) {
Statement stmt = null;
ResultSet rs = null;
StringBuffer strPre = new StringBuffer("");
for(int i=0; i<level; i++) {
strPre.append(" ");
}
try {
stmt = conn.createStatement();
String sql = "select * from article where pid = " + id;
rs = stmt.executeQuery(sql);
while(rs.next()) {
System.out.println(strPre + rs.getString("cont"));
if(rs.getInt("isleaf") != 0)
tree(conn, rs.getInt("id"), level + 1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
大家好,我在学习的过程里看到一段代码,StringBuffer strPre = new StringBuffer("");在这里是什么意思?起到什么作用啊?我是新手,请大家赐教
Statement stmt = null;
ResultSet rs = null;
StringBuffer strPre = new StringBuffer("");
for(int i=0; i<level; i++) {
strPre.append(" ");
}
try {
stmt = conn.createStatement();
String sql = "select * from article where pid = " + id;
rs = stmt.executeQuery(sql);
while(rs.next()) {
System.out.println(strPre + rs.getString("cont"));
if(rs.getInt("isleaf") != 0)
tree(conn, rs.getInt("id"), level + 1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
大家好,我在学习的过程里看到一段代码,StringBuffer strPre = new StringBuffer("");在这里是什么意思?起到什么作用啊?我是新手,请大家赐教
for(int i=0; i <level; i++) {
strPre.append(" ");
} 这个就是每一个level都加上" "的作用..
用String也行,level的数量真的大到会影响效率时,用StringBuffer或者StringBuilder,要不就String,不会太影响你的执行效率的。
String的对象创建后,内容无法改变。
而StringBuffer中的append()方法,replaceAll()等方法可以
改变字符缓冲区中的字符串内容。在这里的append()是往字符串后面追加内容。
StringBuffer是可变长度的字符串类型