package sqlconnect;

import java.sql.ResultSet;
import java.util.ArrayList;

public class Que {
    private static ArrayList<String> getAttribute(Item item,ResultSet rs){
        ArrayList<String> arrayList=new ArrayList<>();
        try{
            for(int i=0;i<item.size;i++){
                String key=item.key.get(i);
                String type=item.type.get(i);
                if(type=="INT") arrayList.add(String.valueOf(rs.getInt(key)));
                else arrayList.add(String.valueOf(rs.getString(key)));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return arrayList;
    }
    public static ArrayList<ArrayList<String>> QueryAll(String table){
        ArrayList<ArrayList<String>> data=new ArrayList<>();
        if(Database.Maps.containsKey(table)==false){
            System.err.println("没有找到该表");
            return data;
        }
        Item item=Database.Maps.get(table);
        String sqlQue="select * from "+table;
        try{
            ResultSet rs=Database.state.executeQuery(sqlQue);
            while(rs.next()){
                data.add(getAttribute(item,rs));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return data;
    }
    public static ArrayList<ArrayList<String>> QueryBook(String name){
        ArrayList<ArrayList<String>> arrayLists=new ArrayList<>();
        name=SQLfilter.filter(name);
        String sqlQue="select book.bookno,bookname,author from book " +
                "join readinghistory rh on book.bookno=rh.bookno " +
                "join student on rh.sno=student.sno where sname='"+name+"'";
        System.out.println(sqlQue);
        Item item=Database.Maps.get("book");
        try{
            ResultSet rs=Database.state.executeQuery(sqlQue);
            while(rs.next()){
                arrayLists.add(getAttribute(item,rs));
            }
        }catch (Exception e){
            System.err.println("查询失败");
            e.printStackTrace();
        }
        return arrayLists;
    }
}
