获取数据以填充JTable netbeans

时间:2014-01-26 06:13:59

标签: java mysql jtable

我已成功连接到MySQL数据库并可以在命令中打印数据,但我想将它们放入JTable中。我知道不允许以下内容,但我该怎么做;

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

正确的方法是;

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

但我不知道1和2代表什么。

真的,我只想获取所有数据,并使用MySQL的名称和价格变量填充JTable。

这是我的DBConnect类;

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);
    }
}
}

1 个答案:

答案 0 :(得分:1)

//全球宣言

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

//向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);

这将帮助您从数据库中获取数据

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;
}