六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 63|回复: 0

java 连接 MySQL (递归实例)

[复制链接]

升级  24.67%

19

主题

19

主题

19

主题

秀才

Rank: 2

积分
87
 楼主| 发表于 2013-2-3 14:35:21 | 显示全部楼层 |阅读模式
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();
}
}

}

}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表