how to populate all items in JTable when corresponding JTextfield is empty

穿精又带淫゛_ 提交于 2019-12-02 08:56:51

First off please note your query is vulnerable to SQL injection attacks. To avoid these issues you need to use PreparedStatement properly:

String val1 = txt_billing2.getText();
...
String val5 = txt_umonth2.getText();

String sql = "SELECT * from airindia_sqlite WHERE BILLING = ? and STATION = ? and INVOICE = ? and AMONTH = ? and UMONTH = ?";
ps = con.prepareStatement(sql);
ps.setObject(1, val1);
...
ps.setObject(5, val5);

Having said this, I'd use an auxiliar class to write WHERE clause given a number of parameters. Something like:

public class WhereClause {

    private Integer currentIndex = 0;
    private Map<Integer, Object> parameters = new HashMap<>();
    private StringBuilder whereClause = null;

    public void addParameter(String columnName, Object value) {
        if(whereClause == null) {
            whereClause = new StringBuilder(" WHERE ");
        } else if (currentIndex > 0) {
            whereClause.append(" AND ");
        }
        whereClause.append(columnName).append(" = ?");
        paramenters.put(++currentIndex, value);
    }

    public String getWhereClause() {
        return whereClause != null ? whereClause.toString() : "";
    }

    public Map<Integer, Object> getParamenters() {
        return parameters;
    }
}

Then you could do something like this to get the appropriate SQL statement:

WhereClause whereClause = new WhereClause();

if(!(txt_billing2.getText().trim().isEmpty())) {
    whereClause.addParameter("BILLING", txt_billing2.getText().trim());
}

...

if(!(txt_umonth2.getText().trim().isEmpty())) {
    whereClause.addParameter("UMONTH ", txt_umonth2.getText().trim());
}

String sql = "SELECT * FROM airindia_sqlite" + whereClause.getWhereClause();
ps = con.prepareStatement(sql);

Map<Integer, Object> parameters = whereClause.getParameters();
for (Integer key : parameters.keySet()) {
    ps.setObject(key, parameters.get(key));
}

rs = ps.executeQuery();

Off-topic

Beware database calls are time consuming tasks and may block the Event Dispatch Thread (a.k.a. EDT) causing the GUI become unresponsive. The EDT is a single and special thread where Swing components creation and update take place. To avoid block this thread consider use a SwingWorker to perform database calls in a background thread and update Swing components in the EDT. See more in Concurrency in Swing trail.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!