您的位置:首页 > 其它

递归方法实现树形数据

2016-05-28 22:37 429 查看
利用递归方法实现数据的树形数据的输出

mysql数据库

create database bbs;

use bbs;

create table article(
id int primary key auto_increment,
pid int,
rootid int,
title varchar(255),
cont text,
pdate datetime,
isleaf int
);
isleaf   0是叶子节点 1代表非叶子节点
public void show() {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
pstmt = conn.prepareStatement("select * from article where id=1");
rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("cont"));//首先输出pid=0(id=1)的cont
tree(conn, rs.getInt("id"), 1);           //调用方法,输出树形
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, pstmt, conn);
}
}

private void tree(Connection conn, int id, int level) {
PreparedStatement pstmt = null;
ResultSet rs = null;
StringBuffer strPre = new StringBuffer("");
for (int i = 0; i < level; i++) {                  //控制缩进
strPre.append("----");
}
try {
pstmt = conn.prepareStatement("select * from article where pid=?");//上一层的id就是这一层的pid,
pstmt.setInt(1, id);                                               //获取到上一层id,也是这一层的pid
rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println(strPre + rs.getString("cont"));           //输出指针所在层的内容
if (rs.getInt("isleaf") != 0) //判断是否是叶子节点,如果不是叶子节点则继续调用tree往下一层走,如果是叶子节点就代表
tree(conn, rs.getInt("id"), level + 1);  //到终端了,不再递归</span>
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCUtils.release(rs, pstmt, null);
}
}
}

class JDBCUtils {

/**
* 关闭连接方法
*
* @param statement
* @param c
*/

public static void release(ResultSet rs, Statement statement, Connection c) {
if (rs != null) {
try {
rs.close();
rs=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
statement=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (c != null) {
try {
c.close();
c=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

/**
* 获取连接mysql方法
* 需要准备jdbc.properties文件
*/
public static Connection getConnection() throws SQLException {
String driverclass = null;
String user = null;
String pwd = null;
String jdbcUrl = null;
Properties pro = new Properties();
try {
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
} catch (IOException e) {
e.printStackTrace();
}
driverclass = pro.getProperty("driver");
user = pro.getProperty("user");
pwd = pro.getProperty("psw");
jdbcUrl = pro.getProperty("jUrl");
try {
Class.forName(driverclass);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection c = DriverManager.getConnection(jdbcUrl, user, pwd);
return c;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: