刷新数据库连接

时间:2012-08-02 15:26:14

标签: java mysql swing

我有一个连接到MySQL数据库的Java应用程序,并使用select语句通过JTable显示状态为“O”的行。我添加了一个鼠标事件,以便在单击所选行后,该行的详细信息将以另一个GUI形式显示。在新表单上发生鼠标事件后,数据库表将更新为状态“R”。当我回到JTable上的原始显示时,我希望不再显示该行。但是,我发现之前选择的行仍然显示在JTable上,我必须退出整个程序,JTable才能刷新更新的状态。

表状态将更新为“R”并且正在使用

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

从每个表单导航。有没有办法刷新数据库连接,这样一旦我回到显示GUI,表格会使用更改后的状态进行更新?

我使用此代码显示:

public class ReceiveOrderedParts extends JFrame{
static Vector<Vector<String>> data = new Vector<Vector<String>>();
static JTable table;
ReceiveOrderedParts(final String st) throws InterruptedException, SQLException{             
    super("Order Details Inquiry");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel topPanel = new JPanel();

    getContentPane().add(topPanel, BorderLayout.PAGE_START);

    Vector<String> headers = new Vector<String>();
    headers.add("Order Number");
    headers.add("Date");       
    headers.add("Part Number");
    headers.add("Part Name");
    headers.add("Application");
    headers.add("Quantity");  
    headers.add("Total Cost");
    headers.add("Supplier");                       
    headers.add("Country");

    getData();

    //this is the model which contain actual body of JTable
    DefaultTableModel model = new DefaultTableModel(data, headers);
    table = new JTable(model);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);       
    //table.enable(false);
    table.addMouseListener(new ReceiveOrderedParts.MyMouseAdapter());
    boolean b = table.isCellEditable(WIDTH, WIDTH);
    b = false;

    header_size();

    JScrollPane scroll = new JScrollPane(table);

    scroll.setHorizontalScrollBarPolicy(
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scroll.setVerticalScrollBarPolicy(
            JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

    getContentPane().add(scroll, BorderLayout.PAGE_START);

    pack();
    setResizable(false);
    setVisible(true);
    setSize(1000, 700);

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyMouseAdapter extends MouseAdapter  {

    public void mousePressed(MouseEvent e)  {         
            int colIdx = table.columnAtPoint(e.getPoint());                
            int rowIdx = table.rowAtPoint(e.getPoint());
           Object obj = table.getModel().getValueAt(rowIdx, colIdx) ;
              String order = obj.toString();                
            JOptionPane.showMessageDialog(null,"Receive Order "+ order + "?", "Success",
                        JOptionPane.INFORMATION_MESSAGE);
                   // return;
        try {
            SelectOrder seo = new SelectOrder(order);
            seo.setVisible(true);
            setVisible(false);
        } catch (InterruptedException ex) {
            Logger.getLogger(ReceiveOrderedParts.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

/**
 * Setting the particular Column Size in JTable
 */
public static void header_size() {
    TableColumn column = table.getColumnModel().getColumn(0);
    column.setPreferredWidth(100);

    column = table.getColumnModel().getColumn(1);
    column.setPreferredWidth(100);
}

/**
 * Fetching Data From MySql Database and storing in a Vector of a Vector to
 * Display in JTable
 */
private static void getData() throws SQLException {
    // Enter Your MySQL Database Table name in below Select Query.
    String str = "select order_number, Part_number, spare_desc, vehicle_app, qnty_ordered,"
            + "seller_name, total_purchases, country, order_date from order_details_table where status = 'O'";
    Connection cn = null;
    ResultSet rs;
    Statement st;

    try {
        // Change the database name, hosty name, 
        // port and password as per MySQL installed in your PC.
        cn = DriverManager.getConnection("jdbc:mysql://"
                + "localhost:3306/test", "root", "gatungo@123");
        st = cn.createStatement();

        rs = st.executeQuery(str);

        while (rs.next()) {
            Vector<String> d = new Vector<String>();

            d.add(rs.getString("order_number"));
            d.add(rs.getString("order_date"));                
            d.add(rs.getString("Part_number"));
            d.add(rs.getString("spare_desc"));
            d.add(rs.getString("vehicle_app"));
            d.add(rs.getString("qnty_ordered"));  
            d.add(rs.getString("total_purchases"));
            d.add(rs.getString("seller_name"));                                                
            d.add(rs.getString("country"));

            d.add("\n\n\n\n\n\n\n");
            data.add(d);

        }
        cn.close();

    } catch (SQLException e) {

        e.printStackTrace();

    }
}
}

我回过头来看看这段代码;

Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "test";
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
conn = DriverManager.getConnection(url + db, "user", "password");
Statement st = conn.createStatement();
String partno = tpart.getText();
String sparedesc = tdesc.getText();
String vapp = tapp.getText();
String qunty = tqnty.getText();
String costper = tcost.getText();
String country = tcountry.getText();
String retail = tretail.getText();
String store = tstore.getText();
String location = tlocation.getText();
String rdate = trdate.getText();
String storeit = "INSERT INTO Store_info_table (Part_number, spare_desc, vehicle_app, qnty_received, cost_per_unit"
        + ", selling_price, country, store_name, store_location, recvd_date) "
        + "VALUES ('" + partno + "', '" + sparedesc + "', '" + vapp + "', '" + qunty + "', '" + costper + "','" + retail + "','" + country + "','" + store + "','" + location + "','" + rdate + "' )";
st.execute(storeit);

String updateOrder = "UPDATE order_details_table set status = 'R' where order_number = '" + order + "'";
st.execute(updateOrder);

JOptionPane.showMessageDialog(null,"Item Stored Successfully", "Success",
        JOptionPane.INFORMATION_MESSAGE);
conn.close();

ReceiveOrderedParts rop = new ReceiveOrderedParts(order);
rop.invalidate();
rop.setVisible(true);
setVisible(false);                        

1 个答案:

答案 0 :(得分:1)

您应该考虑实施observer pattern来处理这种情况。因此,当更新新表单中的数据时,会发送通知,并通过从数据库中提取新值来更新原始表。