I have a JFrame that has 3 JTextfields and 2 JDatechooser, what I am trying to do is if only one JTextfield has something typed in it and I press the search button, then I will be able to retrieve the data to JTable, but the problem is I have to fill out all JTextFileds and JDatechooser in order to retrieve data. My idea is to ignore null JTextfields and JTdatechooser if only one JTextfield has the keyword I want ?? Any suggestions ?? Thanks in advance,
public ArrayList<BillsRecord> getBillRecordByID(int EmpCode, String Fname, String Lname, String sDate, String eDate) throws SQLException {
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE B.EMP_ID = ? "
+ " OR E.FNAME = ? "
+ " OR E.LNAME = ? "
+ " OR DATE BETWEEN ? AND ? "
+ " ORDER BY B.DATE";
DBConnection con = new DBConnection();
Connection connect = con.getConnection();
PreparedStatement ps = null;
ArrayList<BillsRecord> records = new ArrayList<>();
try {
ps = connect.prepareStatement(sql);
ps.setInt(1, EmpCode);
ps.setString(2, Fname);
ps.setString(3, Lname);
ps.setString(4, sDate);
ps.setString(5, eDate);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
BillsRecord billrec = new BillsRecord();
billrec.setDATE(rs.getString("DT"));
billrec.setEMP_ID(rs.getInt("EMP_ID"));
billrec.setFNAME(rs.getString("FNAME"));
billrec.setLNAME(rs.getString("LNAME"));
billrec.setMONEY_SENT(rs.getDouble("MONEY_SENT"));
billrec.setRENT(rs.getDouble("RENT"));
billrec.setPHONE(rs.getDouble("PHONE"));
billrec.setGAS(rs.getDouble("GAS"));
billrec.setELECTRICITY(rs.getDouble("ELECTRICITY"));
billrec.setINTERNET(rs.getDouble("INTERNET"));
billrec.setOTHER(rs.getDouble("OTHER"));
records.add(billrec);
return records;
}
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
if (ps != null) {
ps.close();
}
if (connect != null) {
connect.close();
}
}
return null;
}
private void search() {
try {
JTextField stxt = ((JTextField) startdatetxt.getDateEditor().getUiComponent());
String sDATE = stxt.getText().trim();
JTextField etxt = ((JTextField) enddatetxt.getDateEditor().getUiComponent());
String eDATE = etxt.getText().trim();
int EMP_ID = Integer.parseInt(this.empidtxt.getText().trim());
String FNAME = this.firstnametxt.getText().trim();
String LNAME = this.lastnametxt.getText().trim();
BillRecordDao billrecdao = new BillRecordDao();
ArrayList<BillsRecord> records = billrecdao.getBillRecordByID(EMP_ID, FNAME, LNAME, sDATE, eDATE);
Object[] tableColumnName = new Object[11];
tableColumnName[0] = "Date";
tableColumnName[1] = "H.License";
tableColumnName[2] = "First Name";
tableColumnName[3] = "Last Name";
tableColumnName[4] = "MONEY SENT";
tableColumnName[5] = "RENT";
tableColumnName[6] = "PHONE";
tableColumnName[7] = "GASE";
tableColumnName[8] = "ELECTRICITY";
tableColumnName[9] = "INTERNET";
tableColumnName[10] = "OTHER";
DefaultTableModel tbd = new DefaultTableModel();
tbd.setColumnIdentifiers(tableColumnName);
this.BillsSummaryTable.setModel(tbd);
Object[] RowRec = new Object[11];
for (int i = 0; i < records.size(); i++) {
RowRec[0] = records.get(i).getDATE();
RowRec[1] = records.get(i).getEMP_ID();
RowRec[2] = records.get(i).getFNAME().toUpperCase();
RowRec[3] = records.get(i).getLNAME().toUpperCase();
RowRec[4] = records.get(i).getMONEY_SENT();
RowRec[5] = records.get(i).getRENT();
RowRec[6] = records.get(i).getPHONE();
RowRec[7] = records.get(i).getGAS();
RowRec[8] = records.get(i).getELECTRICITY();
RowRec[9] = records.get(i).getINTERNET();
RowRec[10] = records.get(i).getOTHER();
tbd.addRow(RowRec);
}
} catch (SQLException e) {
System.out.println(e.toString());
}
}
Basically, you need to create a variable/dynamic query based on the available values
Now, you can do this using something like StringBuilder or even storing each query element in a List or array, but you always end up with the "trailing OR" problem (you need to know when you've got to the last element and not append the "OR" to the String or remove the trailing "OR" from the resulting String). While not difficult, it's just a pain.
However, if you're using Java 8, you can use StringJoiner!
StringJoiner sj = new StringJoiner(" OR ");
String sql = "SELECT B.DATE AS DT, B.EMP_ID, E.FNAME, E.LNAME, MONEY_SENT, RENT, PHONE, GAS, ELECTRICITY, INTERNET, OTHER"
+ " FROM EMPLOYEE E INNER JOIN BILLS B ON E.EMP_ID = B.EMP_ID"
+ " WHERE ";
List values = new ArrayList();
// EmpCode MUST be a Integer, so it can be null
if (EmpCode != null) {
sj.add("B.EMP_ID = ?");
values.add(EmpCode);
}
if (FName != null) {
sj.add("E.FNAME = ?");
values.add(FName);
}
if (LName != null) {
sj.add("E.LNAME = ?");
values.add(LName);
}
if (sDate != null && eDate != null) {
sj.add("DATE BETWEEN ? AND ?");
values.add(sDate);
values.add(eDate);
}
sql += sj.toString();
Connection connect = null;
try (PreparedStatement ps = connect.prepareStatement(sql)) {
for (int index = 0; index < values.size(); index++) {
ps.setObject(index + 1, values.get(index));
}
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
//...
}
}
} catch (SQLException exp) {
exp.printStackTrace();
}
You might also like to have a look at The try-with-resources Statement and have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
Related
Form 1 is the textfield located
private void tblOrgMouseClicked(java.awt.event.MouseEvent evt) {
Connection cn = null;
Statement st = null;
ResultSet rss = null;
btnSave.setEnabled(false);
btnUpdate.setEnabled(true);
btnDelete.setEnabled(true);
try {
int row = tblOrg.getSelectedRow();
String cell_click = (tblOrg.getModel().getValueAt(row, 0).toString());
String sql = "SELECT * FROM tbl_organization WHERE org_id = '" + cell_click + "'";
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_organization?zeroDateTimeBehavior=convertToNull", "root", "");
st = cn.prepareStatement(sql);
rss = st.executeQuery(sql);
if (rss.next()) {
String addid = rss.getString("org_id");
txtOrgID.setText(addid);
String addname = rss.getString("org_name");
txtOrgName.setText(addname);
String adddesc = rss.getString("org_description");
txtOrgDesc.setText(adddesc);
String addadviser = rss.getString("org_adviser");
txtAdviserName.setText(addadviser);
}
} catch (Exception e) {
}
}
Form 2 is the Jtable
private void tblAdviserList2MouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
Connection cn = null;
Statement st = null;
ResultSet rss = null;
String ab = " ";
try {
int row = tblAdviserList2.getSelectedRow();
String cell_click = (tblAdviserList2.getModel().getValueAt(row, 0).toString());
String sql = "SELECT * FROM tbl_adviser WHERE adviser_id = '" + cell_click + "'";
cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_organization?zeroDateTimeBehavior=convertToNull", "root", "");
st = cn.prepareStatement(sql);
rss = st.executeQuery(sql);
if (rss.next()) {
String addid = rss.getString("firstname").concat(ab).concat(rss.getString("middlename")).concat(ab).concat(rss.getString("lastname"));
new FrmOrganization(addid);
this.setVisible(false);
}
} catch (Exception e) {
}
}
To get the value from a particular cell:
Object cellValue = table.getValueAt(row, col);
Alternatively, you can create a TableModel where each row represents a person object, and add a method on that.
I create this code for get column name in sql databases. But now I ant to modify above code for get all table data with column name. Then get all data and convert to jsonarray and pass. How I modify this code for get all table data with column name.
#Override
public JSONArray getarray(String sheetName) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
con.setAutoCommit(false);
PreparedStatement pstm = null;
Statement stmt = null;
//-----------------------Drop earliye table -------------------------------------------------------------
try {
String sqldrop = "select COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='" + sheetName.replaceAll(" ", "_") + "'";
System.out.println(sqldrop);
PreparedStatement mypstmt = con.prepareStatement(sqldrop);
ResultSet resultSet = mypstmt.executeQuery();
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < total_rows; i++) {
String columnName = resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase();
Object columnValue = resultSet.getObject(i + 1).toString().replaceAll("_", " ");
// if value in DB is null, then we set it to default value
if (columnValue == null) {
columnValue = "null";
}
/*
Next if block is a hack. In case when in db we have values like price and price1 there's a bug in jdbc -
both this names are getting stored as price in ResulSet. Therefore when we store second column value,
we overwrite original value of price. To avoid that, i simply add 1 to be consistent with DB.
*/
if (obj.has(columnName)) {
columnName += "1";
}
obj.put(columnName, columnValue);
}
jsonArray.put(obj);
}
mypstmt.close();
con.commit();
return jsonArray;
} catch (Exception e) {
System.out.println("There is no exist earlyer databases table!..... :( :( :( **************** " + sheetName.replaceAll(" ", "_"));
}
//----------------------------------------------------------------------------
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (SQLException ex) {
Logger.getLogger(PassArrayDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("%%%%%%%%%%");
return null;
}
My target is get all data with column name and above data pass html page as a json. So if you have any method for get all data with column name is suitable for me.
// code starts here
// This method retrieves all data from a mysql table...
public void retrieveAllData( String host, String user, String pass, String query) {
JTextArea textArea = new JTextArea();
try(
Connection connection = DriverManager.getConnection( host, user, pass )
Statement statement = connection.createStatement()
ResultSet resultSet = statement.executeQuery(query)) {
ResultSetMetaData metaData = resultSet.getMetaData();
int totalColumns = metaData.getColumnCount();
for( int i = 1; i <= totalColumns; i++ ) {
textArea.append( String.format( "%-8s\t", metaData.getColumnName(i) ) );
}
textArea.append( "\n" );
while( resultSet.next() ) {
for( int i = 1; i <= totalColumns; i++ ) {
Object object = resultSet.getObject(i).toString();
textArea.append( String.format("%-8s\t", object) );
}
textArea.append( "\n" );
}
}
}
See Below. rs.getString("tags") is subquery with more than 1 row. I want to iterate that subquery(rs.getString("tags") ---- Like rs.next().
while (rs.next()) {
emailDto emaildto = new emailDto();
emaildto.setMid(rs.getInt("id"));
emaildto.setSub(rs.getString("sub"));
emaildto.setMessage(rs.getString("message"));
while(rs.getString("tags").next()){
arrtags[i] = rs.getString(1);
}
emaildto.setTags(arrtags);
rs.getString("tags") does not work --- and contain more than 1 rows. How to extract it. Is there any technique?
Try something like this:
Array tagsArray = rs.getArray("tags");
String[] tags = (String[])tagsArray.getArray();
this is not answer. this is complete code
List emails = new ArrayList();
String listQuery = "select mid, sub, message, "
+ " (select emailid from sub_ids where sub_ids.messageid= sub_mail_list.mid ) // this query fetch more than one row.
as refid"
+ " from sub_mail_list";
PreparedStatement ps = null;
ResultSet rs;
try {
ps = DatabaseConnectionUtil.getConnection().prepareStatement(
listQuery);
rs = ps.executeQuery(listQuery);
while (rs.next()) {
emailDto emaildto = new emailDto();
emaildto.setMid(rs.getInt("mid"));
emaildto.setSub(rs.getString("sub"));
emaildto.setMessage(rs.getString("message"));
Array tagsArray = rs.getArray("refid");
List<vtbDto> vtbdtosvr = new ArrayList<vtbDto>();
int[] tags = (int[])tagsArray.getArray();
for (int i = 0; i < tags.length; i++) {
vtbDto vtbdto = new vtbDto();
vtbdto.setRefid(tags[i]);
vtbdtosvr.add(vtbdto);
}
emaildto.setAr(tagsArray);
emails.add(emaildto);
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
DatabaseConnectionUtil.closeAll(ps);
}
return emails;
And this is code to print function
List emailDtos = emaildao.getAllemails();
for (emailDto emailDto2 : emailDtos) {
System.out.println( emailDto2.getMid());
System.out.println( emailDto2.getSub());
System.out.println( emailDto2.getMessage());
List<vtbDto> vtbdtos= emailDto2.getVtbdtolst();
for (vtbDto vtbdto2 : vtbdtos) {
System.out.print(vtbdto2.getRefid() + ", ");
}
}
and the console print "Subquery returns more than 1 row";
I use a jTable jquery for jsp page, it work very well. It can display the showing count records in bottom right of table well (e.g. Showing 1-10 of 22). When I insert the Filtering into the page, the showing count record is not correctly.
I follow this for Filtering: http://www.jtable.org/Demo/Filtering
How to customize the code for showing count record (I use java-jsp and sql server). Sorry for my English language :))
Here is the code I am using right now in controller.
if (action.equals("list")) {
try {
int startPageIndex = Integer.parseInt(request.getParameter("jtStartIndex"));
int numRecordsPerPage = Integer.parseInt(request.getParameter("jtPageSize"));
String jtSorting = null;
//Fetch Data from Rejected_Product Table
lstSite = dao.**getAllSite**(filter_site, startPageIndex, numRecordsPerPage, jtSorting);
//Get Total Record Count for Pagination
int siteCount = dao.**getSiteCount**();
//Convert Java Object to Json
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(lstSite, new TypeToken<List<Site>>() {
}.getType());
JsonArray jsonArray = element.getAsJsonArray();
String listData = jsonArray.toString();
//Return Json in the format required by jTable plugin
listData = "{\"Result\":\"OK\",\"Records\":"+listData+",\"TotalRecordCount\":"+siteCount+"}";
response.getWriter().print(listData);
System.out.println(listData);
} catch (Exception ex) {
String error = "{\"Result\":\"ERROR\",\"Message\":" + ex.getStackTrace() + "}";
response.getWriter().print(error);
ex.printStackTrace();
}
}
and here method getAllSite:
public List<Site> getAllSite (FilterSite filter_site, int jtStartIndex, int jtPageSize, String jtSorting) {
List<Site> siteList = new ArrayList<Site>();
String query = "";
String siteQ = filter_site.getSite();
String clientQ = filter_site.getClient(); // wait
String locationQ = filter_site.getLocation();
if (locationQ.isEmpty()) {
locationQ = "";
} else {
locationQ = "and location like '%"+locationQ+"' ";
}
String site_idQ = filter_site.getSite_id();
if (site_idQ.isEmpty()) {
site_idQ = "";
} else {
site_idQ = "and site_id = '"+site_idQ+"' ";
}
String divisionQ = filter_site.getDivision();
if (divisionQ.isEmpty()) {
divisionQ = "";
} else {
divisionQ = "and division = '"+divisionQ+"' ";
}
int range = jtStartIndex+jtPageSize;
query = "SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY CODE) as row FROM [site]) a "
+ "WHERE (code like '%"+siteQ+"' "+locationQ+site_idQ+divisionQ+") "
+ "and row > "+jtStartIndex+" and row <= "+range;
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query);
System.out.println("query : "+query);
while (rs.next()) {
Site sitebean = new Site();
sitebean.setName(rs.getString("name"));
sitebean.setCode(rs.getString("code"));
.....
siteList.add(sitebean);
}
} catch (SQLException e) {
e.printStackTrace();
}
return siteList;
}
and here method getSiteCount :
public int getSiteCount () {
int count = 0;
String query = "SELECT COUNT(*) as count FROM [site] ";
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query);
while (rs.next()) {
count = rs.getInt("count");
}
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
If you mean by "not correctly" that the row count is larger than expected, then the solution would be to include the where clause in the siteCount query.
WHERE (code like '%"+siteQ+"' "+locationQ+site_idQ+divisionQ+")
I have 2 Frames let's name them "Request" and "Confirm". Now when clicking a Button in "Request" the Frame "Confirm" is called. And when clicking "yes" a SQL Statement should be executed. The thing is that the SQL Statement is in class "Request". The Class "Confirm" should be called from other Frames too, so I don't want to make an Action Listener on the Button "yes" in "Confirm". I what to get a boolen by clicking the "yes" Button. If its true the statement in 'Request" should be executed.
How I can do this?
ReqBnt.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
if (arg0.getSource() == ReqBnt) {
String VendN = txtVendN.getText();
String VendSN = txtVendSN.getText();
String Ad = txtAd.getText();
String Ads = txtAds.getText();
String City = txtCity.getText();
String Zip = txtZip.getText();
String UID = txtUID.getText();
String Reg = txtReg.getText();
String Rep = txtRep.getText();
String Tel = txtTel.getText();
String Fax = txtFax.getText();
String Mail = txtMail.getText();
String Iban = txtIban.getText();
String Bic = txtBic.getText();
String BInst = txtBInst.getText();
String VendInfo = txtVendInfo.getText();
String Flag = "Y";
String PT = comboPT.getSelectedItem().toString();
String Ctry = comboCtry.getSelectedItem().toString();
try{
try {
String sqlx = "SELECT `Abbreviation 2`, `Country English` From `database`.`country_master` " +
"WHERE `Country English` = '" + Ctry + "'";
PreparedStatement pstx = conn.prepareStatement(sqlx);
ResultSet rs = pstx.executeQuery();
while (rs.next()){
partCode = rs.getString("Abbreviation 2");
}}catch (Exception ex) {
System.out.println("Abbreviation Not Found");
}
String sqlFind = "Select max(substring(`Vendor Code`, 3)) From `database`.`vendor_master`";
try {
PreparedStatement pstFind = conn.prepareStatement(sqlFind);
ResultSet rs = pstFind.executeQuery();
while (rs.next()){
partNo = rs.getInt("Vendor Code")+1;
}}catch (Exception ex) {
partNo = 10001;
}
String VendC = partCode+partNo;
try {
String sqlx = "SELECT `Abbreviation Use`, `Country English` From `database`.`country_master` " +
"WHERE `Country English` = '" + Ctry + "'";
PreparedStatement pstx = conn.prepareStatement(sqlx);
ResultSet rs = pstx.executeQuery();
while (rs.next()){
CtryC = rs.getString("Abbreviation Use");
}}catch (Exception ex) {
System.out.println("Abbreviation Not Found");
}
Calendar currentDate = Calendar.getInstance(); //Get the current date
SimpleDateFormat formatter= new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
//if
// 1.step: check if there are null values
// 2.step: if there are no null values -> call frame "Confirm"
// 3.step: if Confirm = true -> execute statement
// if Confitm = fals -> do nothing
try {
String sql = "INSERT INTO `database`.`vendor_master`(`Vendor Code`,`Vendor Full Name`,`Vendor Short Name`,"+
"`Address`,`Address Suffix`,`ZIP Code`,`City`,`Country`,`Country Code`,`UID No`,`Registration No`,"+
"`Payment Term`,`Creation Date`,`IBAN`,`BIC`,`Banking Institution`,`Representive`,`Email Address`,"+
"`Telefon No`,`Fax`,`Vendor Information`,`Active Flag`) "+
"Values('"+VendC+"','"+VendN+"','"+VendSN+"','"+Ad+"','"+Ads+"','"+Zip+"','"+City+"','"+Ctry+"','"+CtryC+"','"+
UID+"','"+Reg+"','"+PT+"','"+dateNow+"','"+Iban+"','"+Bic+"','"+BInst+"','"+Rep+"','"+Mail+"','"+Tel+"','"+
Fax+"','"+VendInfo+"','"+Flag+"')";
PreparedStatement pstExecute = conn.prepareStatement(sql);
pstExecute.execute();
System.out.println("Vendor Registered");
}catch (Exception ex) {
System.out.println("Please insert required Fields!");
}
///end if
}catch (Exception ex) {
System.out.println("Error: "+ex);
}
}
}
});
Try using a JDialog instead:
int dialogResult = JOptionPane.showConfirmDialog (
null,
"Are you sure you want to do that?",
"Warning",
JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
//Do a thing here
}
You can Take a look at the dialog here:
http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
You can even extend JDialog instead if you want more functionality.