Populate table from database
I'm trying to retreive rows from my database and populate a table. I don't understand where the problem is with this code:
if ((report.getMsg()=="selectEventoAll") && (report.getEsito()==1))
{
DefaultTableModel dtm = new DefaultTableModel();
eventi_tb.setModel(dtm);
try
{
ResultSet res_eventi = report开发者_如何学运维.getRes();
i = 0;
Object[][] datiEventi = new Object[report.getRowCount()][5];
while(res_eventi.next())
{
j = 0;
while (j < 5)
{
datiEventi[i][j] = res_eventi.getObject(j+2);
j++;
}
dtm.addRow(datiEventi[i]);
i++;
}
}
This is a bad design. You're mixing your UI and database together. Your code is no good if you change from Swing to a web UI. It's harder to test and debug this way, too.
Break the problem into two pieces: database access and Swing display.
Have one object that does nothing but query for results and load them into a data structure.
Have another that does nothing but accept a data structure and load it into your Swing UI for display.
Your application will have the database decoupled from the user interface. Your testing and debugging life will be easier.
Post more code and perhaps an error message would help us help you faster than guessing.
The loop over the columns in the result set looks suspicious to me. They run from 1 to the number of columns, but you start at 2. Why? If your query has five or fewer columns you'll have an issue there.
Are you sure that your ResultSet contains any rows?
Are you sure that some exception is not occurring before the call to addRow
? You're in a try block, what does the catch block do?
精彩评论