實現論壇樹狀結構演算法眾多,本文介紹一種「不使用遞歸」的演算法,並提供完整資料庫結構、建表 SQL、MySQL 連線 Bean 程式碼。
| 欄位 | 資料型態 | 說明 |
|---|---|---|
| BBSID | 自動編號 | 主鍵 |
| RootID | Int | 根文章 ID,根文章時 RootID = ID |
| FID | Int | 父文章 ID,上一層文章 ID,根文章時 FID = 0 |
| DEPTH | Int | 層級深度,根文章 Level=0,回覆遞增 |
| BBSSubject | Char | 主旨 |
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)
)
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)提升效能。