我有一个 JTable 的问题,即当从 MySQL 表返回超过 1 行时,JTable 只显示 1 条记录 - (最后一条),但是当我尝试简单时System.out.print
,它会显示所有记录。这是我的代码:
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://xxx.xx.xxx.xx:3306/";
String dbName = "smartcart";
String driver = "com.mysql.jdbc.Driver";
String userName = "xxx";
String password = "xxx";
Statement stmt = null;
ResultSet rs = null;
cartID=jTextField1.getText().trim();
if(cartID.matches("(\\w*)") && !cartID.isEmpty())
{
jLabel2.setText("Searching.....");
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
stmt = conn.createStatement();
String query = "SELECT * FROM user_stock WHERE cartID="+cartID;
rs = stmt.executeQuery(query);
jInternalFrame1.setVisible(true);
while (rs.next()) {
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{rs.getString("id"), rs.getString("product_name"), rs.getString("product_code"), rs.getString("product_quantity"), rs.getString("product_price"), "0"}
},
new String [] {
"Product No.", "Product Name", "Product Code", "Product Quantity", "Product Price", "Discount"
}
));
}
conn.close();
System.out.println("Disconnected from database");
}
catch (Exception e) {
e.printStackTrace();
}
}