package com.next.ebuy.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import com.next.ebuy.entity.ProductType;
//测试方法
public class Test {
private Connection con=null;
private Statement stmt = null;
private ResultSet rs =null;
/**
* @param Oracle数据库
* @throws ParseException
//main方法测试
*/
public static void main(String[] args) {
//getConnection();
Test t = new Test();
List<ProductType> list = t.getList(0);
t.print(list, 0, "--");
}
//JDBC技术,获得数据库 连接
public Connection getConnection (){
try {
Class.forName("oracle.jdbc.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","Ebuy","t09");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
//遍历数据库,拿到所有元素集合
public List<ProductType> getList(int id){
getConnection();
List<ProductType> list = new ArrayList<ProductType>();
String sql ;
if(id==0){
sql="select * from t_product_type where p_id is null";
}else{
sql="select * from t_product_type where p_id ="+id;
}
try {
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
ProductType p = new ProductType();
p.setId(rs.getInt("protype_id"));
p.setName(rs.getString("name"));
p.setP_id(rs.getInt("p_id"));
list.add(p);
}
for(ProductType p:list){
//开始递归
List<ProductType> childrenList = getList(p.getId());
p.setChildren(childrenList);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
//在控制台打印有层次的菜单
public void print(List<ProductType> list,int n,String s){
String sp="";
for(int i=0;i<n;i++){
sp =sp+" ";
}
String ps =sp+s;
for(ProductType p:list){
System.out.println(ps+p.getName());
if(p.getChildren().size()>0){
//递归打印
print(p.getChildren(),n+2,s);
}
}
}
}
//实体类,get,set方法自己添上
//打印效果如下