简体   繁体   中英

Java - Calling super.toString() to format a resultset

I can print my resultset with no problem when querying my database. I need to use super.toString method which is overridden in my super class giving me the format I want the resultset to be displayed in.

 res = stmt.executeQuery("Select * from registrar.student ");  
 System.out.println("\nAll records in your table:");  
 while (res.next()) {  
     String data = "";  
     data += res.getString("studentID") + "  "  
          + res.getString("firstName") + " "  
          + res.getString("lastName") + " "  
          + res.getDouble("GPA")+ " "  
          + res.getString("status") + " "  
          + res.getString("mentor") +" "  
          + res.getString("level")+"\n";  
     System.out.println(data); 

How can I add super.toString() to format the display of my data?

You can't. Your super does not know anything about the data in your child class, unless the data you are formatting is located in your parent, and set in the child.

However, as your code is showing a String object being created as a local variable, there is no way your super will know anything about this variable.

The purpose of the toString is to output the representation of that object, which usually means the attributes of that object.

You can always call super.foo() from your class. This invokes the super class method. Obviously yo cannot choose which implementation of foo() you call if you are doing it outside the class. In this case you always call the "last" overridden version. This is called polymorphism.

I have tried this

public static void printRecord(ResultSet rs)
    {
        try {
            ResultSetMetaData rsmd=rs.getMetaData();

            int totalColumns=rsmd.getColumnCount();

            StringBuilder sb=new StringBuilder();
            String columnName=null;

            sb.append("[ ");
            for(int i=1;i<=totalColumns;i++)
            {
                columnName=rsmd.getColumnName(i);

                sb.append(columnName);
                sb.append(":");
                sb.append(rs.getString(i));

                if(i!=(totalColumns-1))
                {
                    sb.append(" , ");
                }
            }
            sb.append(" ]");

            System.out.println(sb.toString());
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM