0

I have successfully connected to MySQL database and can print data in the command but I want to place them into a JTable. I know the following is not allowed but how can I do this;

jTable1.setValueAt(connect.rs.getString("name"), row, 0);
jTable1.setValueAt(connect.rs.getString("price"), row, 1);

The correct way is;

jTable1.setValueAt(connect.rs.getString(1), row, 0);
jTable1.setValueAt(connect.rs.getString(2), row, 1);

But I don't know what 1 and 2 represents.

Really I just want to get all the data and populate the JTable with name and price variables of MySQL.

Here is my DBConnect class;

import java.sql.*;


public class DBConnect {

private Connection con;
private Statement st;
public ResultSet rs;
public String name;
public String ph;
public DBConnect(){
   try{
       Class.forName("com.mysql.jdbc.Driver");

       con = DriverManager.getConnection("jdbc:mysql://buiud.com:3306/buiud458_androidhive","XXX","XXX");

       st = con.createStatement();

   } 
   catch(Exception ex){
       System.out.println("Err: "+ex);
   }
}

public void getData(){
    try{
        String query = "select * from products";
        rs = st.executeQuery(query);
        System.out.println("Records from database");
        while(rs.next()){
            name = rs.getString("name");
            ph = rs.getString("price");
            System.out.println("Name: "+name+"    "+"Price: "+ph);
        }
    }catch(Exception ex){
        System.out.println("ERR: "+ex);
    }
}
}
SoftwareEnthusiast
  • 271
  • 2
  • 9
  • 26
  • Have you taken a look at the following [question](http://stackoverflow.com/questions/8775076/jtablejdbc-easiest-way)? – Kent Shikama Jan 26 '14 at 06:36

1 Answers1

0

//Global Declaration

private Vector<Vector<String>> data; //used for data from database
private Vector<String> header; //used to store data header

//Display info to JTable

data = get();

//create header for the table
header = new Vector<String>();
header.add("Column1"); 
header.add("Column2");
...
model=new DefaultTableModel(data,header);
table = new JTable(model);

This will help you to get data from database

get(){
Vector<Vector<String>> doublevector = new Vector<Vector<String>>();

Connection conn = dbConnection();//Your Database connection code
PreparedStatement pre1 = conn.prepareStatement("select * from Table");

ResultSet rs1 = pre1.executeQuery();
while(rs1.next())
{
Vector<String> singlevector = new Vector<String>();
singlevector.add(rs1.getString(1)); 
singlevector.add(rs1.getString(2)); 
....
doublevector.add(singlevector);

}

return doublevector;
}
ravibagul91
  • 20,072
  • 5
  • 36
  • 59