首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> JSP 程式設計 >> 關於JSP

JSP 實現論壇樹狀結構:非遞歸演算法與資料庫設計

     編輯:關於JSP

實現論壇樹狀結構演算法眾多,本文介紹一種「不使用遞歸」的演算法,並提供完整資料庫結構、建表 SQL、MySQL 連線 Bean 程式碼。

1. 資料表結構:mybbslist

欄位資料型態說明
BBSID自動編號主鍵
RootIDInt根文章 ID,根文章時 RootID = ID
FIDInt父文章 ID,上一層文章 ID,根文章時 FID = 0
DEPTHInt層級深度,根文章 Level=0,回覆遞增
BBSSubjectChar主旨

2. 建表 SQL (MySQL)

create table mybbslist (
    forumID int(20) not null,
    bbsID int auto_increment primary key,
    rootid int(20) not null,
    fid int(20) not null,
    depth int(20) not null,
    userID int(20) not null,
    bbsUser varchar(24) not null,
    bbsSubject varchar(100) not null,
    bbsContent text,
    bbsTime varchar(30),
    bbsRead int(20),
    bbsReply int(20),
    INDEX forumID (forumID)
)

3. MySQL 連線 Bean:netzero.mydb

package netzero;
import java.sql.*;
public class mydb {
    String driverName = "org.gjt.mm.mysql.Driver";
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    String connURL = "jdbc:mysql://localhost/mybbs?user=root&password=how&useUnicode=true&characterEncode=8859_1";

    public mydb() {
        try { Class.forName(driverName); }
        catch (ClassNotFoundException e) { System.err.println("netzero(String): " + e.getMessage()); }
    }

    public ResultSet executeQuery(String sql) throws SQLException {
        conn = DriverManager.getConnection(connURL);
        stmt = conn.createStatement();
        rs = stmt.executeQuery(sql);
        return rs;
    }

    public boolean closeConn() {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
            return true;
        } catch (SQLException ex) {
            System.err.println("closeConn: " + ex.getMessage());
            return false;
        }
    }
}

此 Bean 封裝資料庫連線、查詢執行與資源關閉,採用傳統 JDBC 模式,適合教學與中小型專案參考。實際生產環境建議使用連線池(如 DBCP、HikariCP)提升效能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved