1

I'm facing a small issue with SQL dates and java which I already search the world on internet about this. The thing is that my program must load all the dates from a SQL table to my Java jtable. I might have to use some sort of conversion from date to string.

I tried by using conversion like this records[0]=rs.getDate("mydate").toString(); but no luck with this.

private void load(String value){
    Conector cc= new Conector();
    Connection cn= cc.conexion();
    //java.util.Date date= new java.util.Date();
    //SimpleDateFormat sdf= new SimpleDateFormat("dd/MM/yyyy");                
    String [] titles={"Dates"};
    String [] records;
    records = new String[1];
    String sql="SELECT * FROM turns WHERE dates LIKE '%"+value+"%'";
    model= new DefaultTableModel(null,titles);       
    try {
        Statement st= cn.createStatement();
        ResultSet rs= st.executeQuery(sql);            
        while (rs.next()) {                
            records[0]=rs.getDate("mydate").toString();
            model.addRow(records);
        }
        tablaturnos.setModel(model);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error:"+e, "Error Message", JOptionPane.ERROR_MESSAGE);
    }
}

Any help is appreciated.

1
  • 2
    Rather then changing the data to meet your requirements, create a custom TableCellRenderer which can format the data Commented Jan 2, 2016 at 19:22

1 Answer 1

2

Start by simply collecting all the dates as Date objects

private void load(String value) {
    Conector cc = new Conector();
    Connection cn = cc.conexion();

    String[] titles = {"Dates"};
    model = new DefaultTableModel(null, titles);
    String sql = "SELECT * FROM turns WHERE dates LIKE ?";

    try (PreparedStatement st = cn.prepareStatement(sql)) {
        st.setString(1, "%" + value + "%");
        try (ResultSet rs = st.executeQuery(sql)) {

            Object[] records = new Object[1];
            while (rs.next()) {
                records[0] = rs.getDate("mydate");
                model.addRow(records);
            }
            tablaturnos.setModel(model);
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error:" + e, "Error Message", JOptionPane.ERROR_MESSAGE);
    }
}

Then use a custom TableCellRenderer to change the formatting to your needs, maybe something like...

public class DateTableCellRenderer extends DefaultTableCellRenderer {
    public static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        if (value instanceof java.util.Date) {
            value = DATE_FORMAT.format(date);
        }
        return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    }

}

Then you can set up the table to use the renderer when it encounters a Date...

tablaturnos.setDefaultRenderer(java.util.Date.class, new DateTableCellRenderer());
tablaturnos.setDefaultRenderer(java.sql.Date.class, new DateTableCellRenderer());

Have a look at Concepts: Editors and Renderers, Using Custom Renderers and How to Use Tables for more details

You'll probably also want to have a look at Using Prepared Statements and The try-with-resources Statement

Sign up to request clarification or add additional context in comments.

5 Comments

I was about to collect all the dates as Date like you said. But, can this be applied on a SQL table that is more than Date fields, like Varchar or this method is Date only?
Yes, In fact, you should model your data as is (or as close to the raw data as possible) and then use things like renderers formatters to display it
@MadProgrammer Assuming his database type is SQL DATE, shouldn't that be value instanceof java.sql.Date (".sql.") rather than value instanceof java.util.Date? And why not specify java.sql.Date throughout that code rather than Object? (sincerely asking, not criticizing, as I do not know for sure)
@BasilBourque java.sql.Date extends java.util.Date so a java.sql.Date can act as a java.util.Date. The main reason for using Object is because it meets the requirements of the API, and as the OP has stated, Date isn't the only type of data they want to add
@BasilBourque Probably, but I'm lazy and it means I don't need another renderer to handle java.sql.Date independently. Some JDBC drivers also work with java.util.Date (and sql.Date), so there's another point of cross over :P Perhaps they'll update the JDBC API to work with the new date/time API in Java 8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.