问题
I am trying to generate a JTable in my Inventory system and I wanna display records from my database table to the JTable when user click the view bill button,Image of my Billing Form.

Database structure
Bill_Master
- Bill_Id (Primary Key INT ):-Stores Bill Number
- Bill_Date (Date): Stores Date Of Bill
- Customer_Name ( VARCHAR(50)): Customer Name
- Total_amt (NUMBER(6)) :Total Bill Amount
- Cash_Disc (Number(2)):Discount
- Grand_Total(Number(6)):Grand Total (Total-Discnt)
UID(VARCHAR(10)) Stores Who Generated the bill.(EMPLOYEE ID)
Bill_Details
- Bill_Detailid(INT PRIMARY KEY) Detailed Bill No.1
- Bill_Id(Foreign Key To Bill_Master)
- Item_Id(Foreign Key To Stock)
- Qty (INT)
- Rate(number(5))
- Total(Number(5))
I want to display the detailed bill when user clicks on View Bill Button by using the query
Select * from Bill_Master Inner join Bill_Details on Bill_Master.Bill_Id=Bill_Details.Bill_Id.
Database Connection Type:ODBC Please help to generate the table.
回答1:
You can get data from ResultSet and Add Each row of table to the DefaultTableModel using vector.
Like following Example:
try {
ResultSetMetaData rm = rs.getMetaData();
int j = rm.getColumnCount();
JTable table=new JTable();
int rowCount = table.getRowCount();
DefaultTableModel model = (DefaultTableModel) table.getModel();
Vector v = null;
if (rowCount == 0) {
while (rs.next()) {
v = new Vector();
for (int i = 1; i <= j; i++) {
String type = rm.getColumnTypeName(i);
// System.out.println(type);
switch (type) {
case "FLOAT":
v.add(rs.getFloat(i));
break;
case "COUNTER":
v.add(rs.getInt(i));
break;
case "VARCHAR":
v.add(rs.getString(i));
break;
case "INTEGER":
v.add(rs.getInt(i));
break;
case "DATETIME":
v.add(rs.getString(i));
break;
case "MEDIUMINT":
v.add(rs.getInt(i));
break;
case "LONGBLOB":
v.add(rs.getTime(i));
break;
default:
v.add(rs.getString(i));
}
}
model.addRow(v);
}
Here model is the DefaultTableModel of the Your table on which you have to add the row. do you get my point? Or any doubt.?
回答2:
while(resultset.next()){
// iterate through the results, get necessary column values add them into table model
Vector v = new Vector();
v.add(resultset.getString(0));
.
.
model.addRow(v)
}
table.setModel(model)
follow some tutorials on how to use jTable
来源:https://stackoverflow.com/questions/19629198/creating-jtable-from-database