递归方法实现树形数据

来源:互联网 发布:mcmc算法原理 编辑:程序博客网 时间:2024/06/07 07:19

利用递归方法实现数据的树形数据的输出

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)的conttree(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,也是这一层的pidrs = 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 blocke.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 blocke.printStackTrace();}}if (statement != null) {try {statement.close();statement=null;} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if (c != null) {try {c.close();c=null;} catch (SQLException e) {// TODO Auto-generated catch blocke.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 blocke.printStackTrace();}Connection c = DriverManager.getConnection(jdbcUrl, user, pwd);return c;}}


0 0
原创粉丝点击