我的数据库中有一些记录,我希望在我的java应用程序GUI中的Jtable上显示。我已经定制了Jtable并添加了一些不在我的数据库中的额外列。 请帮助。下面的代码仅显示单个列中的单个记录(特定的描述列)
public NewJFrame() {
ArrayList data = new ArrayList();
initComponents();
okay.setVisible(true);
try {
String myDriver = "com.mysql.cj.jdbc.Driver";
String myUrl = "jdbc:mysql://localhost:3306/lostfound";
Class.forName(myDriver);
Connection c = DriverManager.getConnection(myUrl, "root", "");
String sql = "SELECT * FROM found";
Statement st = c.createStatement();
// execute the query, and get a java resultset
ResultSet rs =st.executeQuery(sql);
while(rs.next())
{
String name = rs.getString("name");
String description = rs.getString("description");
String location = rs.getString("location");
jTable2.getModel().setValueAt(name, WIDTH, ICONIFIED);
jTable2.getModel().setValueAt(description, WIDTH, ICONIFIED);
jTable2.getModel().setValueAt(location, WIDTH, ICONIFIED);
}
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
jTable2.show();
}
答案 0 :(得分:0)
您要将 resultSet
数据分配到单行和列,您需要一个row
计数器&为每一行增加它,如下所示:
int row=0;
while(rs.next()) {
String name = rs.getString("name");
String description = rs.getString("description");
String location = rs.getString("location");
jTable2.getModel().setValueAt(name, row, 0);//name at column 0 always
jTable2.getModel().setValueAt(description, row, 1);//desc at column 1 always
jTable2.getModel().setValueAt(location, row, 2);//location at column 2 always
row++;//increment row counter for each record
}