|
|
import java.sql.*;
public class ArticleTree {
static Connection conn = null;
static int id = 0;
static int level = -1;
static ResultSet rs =null;
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager
.getConnection("jdbc:mysql://localhost/bbs?user=root&password=root");
tree(conn,id);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static void tree(Connection conn,int id){
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
String sql = "select * from article where pid ="+id;
rs = stmt.executeQuery(sql);
level++;
StringBuffer strBuf = new StringBuffer("");
for(int i=0;i<level;i++){
strBuf.append(" ");
}
while (rs.next()) {
System.out.println(strBuf+rs.getString(4));
//System.out.println(id);
if(rs.getInt(7)==1){
id = rs.getInt("id");
tree(conn,id);
level--;
}
}
} 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();
}
}
}
} |
|