Create and View the Database Table in Java Swing


Download the database and jar file here download

      1.Create Java Project in Netbeans

      2.Create JFrame form

     3.Drag & Drop JTable


    4.Delete the predefined columns




   5.Then the jtable look like this


   6.Insert this getTable() method in your class 

public JTable getTable(int value)throws Exception{
String query=null;
query="select * from jsample where id='"+value+"'";
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/path","root","root");
Statement s1=con.createStatement();
DefaultTableModel dm=new DefaultTableModel();
ResultSet rs=s1.executeQuery(query );
ResultSetMetaData rsmd=rs.getMetaData();
//Coding to get columns-
int cols=rsmd.getColumnCount();
String c[]=new String[cols];
for(int i=0;i<cols;i++){
c[i]=rsmd.getColumnName(i+1);
dm.addColumn(c[i]);
}
//get data from rows
Object row[]=new Object[cols];
while(rs.next()){
for(int i=0;i<cols;i++){
row[i]=rs.getString(i+1);
}
dm.addRow(row);
}
jTable1.setModel(dm);     //change your table name here
con.close();
return jTable1;                 //change your table name here
  }

   7.Call your method from your Action 

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
getTable(1);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}

  8.Output






1 comments:

  1. Unknown said...:

    Nice post very helpful

    dbakings

Post a Comment

 
java4practices © 2013 | Designed by Ganesh Rengarajan