I am trying to load data from MySQL into my Application, where I have a jTable. I want to load only 100 rows using a query, and I can do that successfully as of now. furthermore, I want to paginate that data, in such a way that if I have the next button, and I click on that, the table should be updated with 100 more records and so on.
This method loads the data into the table:
public void showTable(){
try{
how.res = how.stat.executeQuery("select * from students order by name ASC limit 100");
while(how.res.next()){
String id = how.res.getString(1);
String name = how.res.getString(2);
String contact = how.res.getString(3);
Object[] content = {id,name,contact};
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.addRow(content);
}
}catch (Exception e){
}
}
I call this method on form Initialization, and now I only get 100 rows into the table, what should I write for the next button to load next 100 rows and update the table?
What I tried:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
numClick+=100;
how.res = how.stat.executeQuery("select * from students offset"+numClick+"");
while(how.res.next()){
String id = how.res.getString(1);
String name = how.res.getString(2);
String contact = how.res.getString(3);
Object[] content = {id,name,contact};
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.addRow(content);
}
}catch (Exception e){
}
}
But this does not give me any result.
Here is the Connection:
public class JoinConnection {
public Connection con;
public Statement stat;
public ResultSet res;
public JoinConnection(){
systemConnection();
}
public void systemConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
con =(com.mysql.jdbc.Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/library","root","");
stat = (Statement) con.createStatement();
}catch(ClassNotFoundException | SQLException e){System.out.println(e);}
}
}
I am using NetBeans with MySQL. if the question is not clear, please tell me for clarification.
EDIT: Thanks to @George Z. We solved the problem by changing the button method into something like below. I am editing the question because I can not write the answer in comments:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try{
numClick+=100;
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setRowCount(0);
how.res = how.stat.executeQuery("select * from students limit "+numClick+" , 100");
while(how.res.next())
{
String id = how.res.getString(1);
String name = how.res.getString(2);
String contact = how.res.getString(3);
Object[] content = {id,name,contact};
model.addRow(content);
}
}catch (SQLException e){
e.printStackTrace();
}
}