JDBC中ResultSetMetaData 的使用

ResultSetMetaData是返回结果集的元集合;结果集中的是记录的集合,元集合是记录中每一项的集合;

public class ResultSetDAO {

    CoffeeDemo coffee = new CoffeeDemo();

    public void viewTabel(String table) throws ClassNotFoundException {
        //1 加载驱动;
         Class.forName ("com.mysql.jdbc.Driver");
        String str = "select * from " + table;
        try (Connection con =ConnectionDemo.connection();//连接数据库;另外创建的连接功能ConnectionDemo.java;
                PreparedStatement patmt = con.prepareStatement(str);
                 ResultSet set = patmt.executeQuery();) {//结果集;
           
            ResultSetMetaData rsmd = set.getMetaData();//元集合;
            int in = rsmd.getColumnCount();
            for (int x = 1; x <= in; x++) {//打印表table中的列名;
                String column = rsmd.getColumnName(x);
                System.out.print(column+"\t");
            }
            System.out.println("");
            while (set.next()) {//打印表table中列名对应的元素;
                for(int x=1;x<=in;x++)
                {
                    System.out.print(set.getString(rsmd.getColumnName(x))+"\t\t");
                }
            }

        } catch (SQLException ex) {
            System.out.println("未连接成功");
            ex.printStackTrace();
        }

    }

}

你可能感兴趣的:(java基础)