I have this method in my database class.and I want to get a part of data from a column which is "dateOfBirth" in MySQL table ,but I don't know why the list.size() is "0" but when i use System.out.println() in my code it will show just the first line of sql table ,although I have two rows!!!
my method:
public static int getBirthPercent(String i) throws SQLException {
Statement stmt = conn.createStatement();
List<String> list = null;
if (i.equals("O")) {
ResultSet rst = stmt.executeQuery("SELECT dateOfBirth from birthtable");
while (rst.next()) {
String s1 = rst.getString(1);
if (rst.wasNull()) {
s1 = null;
}
String s2 = s1.substring(s1.length() - 4);
int s3 = Integer.parseInt(s2);
if (list == null && s3 < 1970) {
list = new ArrayList<String>();
list.add(s2);
} else {
list = new ArrayList<String>(0);
}
}
}
if (i.equals("N")) {
ResultSet rst = stmt.executeQuery("SELECT dateOfBirth from birthtable");
while (rst.next()) {
String s1 = rst.getString(1);
if (rst.wasNull()) {
s1 = null;
}
String s2 = s1.substring(s1.length() - 4);
int s3 = Integer.parseInt(s2);
if (list == null && s3 > 2000) {
list = new ArrayList<String>();
list.add(s2);
System.out.println(list);
} else {
list = new ArrayList<String>(0);
}
}
}
it will return "0" for all "if" situation but the System.out.println() ,shows [2006] which is one of my row's column's year,although I have two rows it must show [2006,2009].but it doesn't!!!
Now try this code, and let us know. Cheers.
public static int getBirthPercent(String i) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rst = null;
List<String> list = new ArrayList<String>();
if (i.equals("O")) {
rst = stmt.executeQuery("SELECT dateOfBirth from birthtable");
while (rst.next()) {
String s1 = rst.getString(1);
if (s1 != null && !s1.isEmpty()) {
String s2 = s1.substring(s1.length() - 4);
int n = Integer.parseInt(s2);
if (n < 1970) {
list.add(s2);
}
}
}
}
if (i.equals("N")) {
rst = stmt.executeQuery("SELECT dateOfBirth from birthtable");
while (rst.next()) {
String s1 = rst.getString(1);
if (s1 != null && !s1.isEmpty()) {
String s2 = s1.substring(s1.length() - 4);
int n = Integer.parseInt(s2);
if (n > 2000) {
list.add(s2);
}
}
}
}
System.out.println(list);
}
Enough refactoring for now. Try to do more for yourself. For example,
look into commons-lang StringUtils to replace null checking,
use Date object to store dates and use rs.getDate() instead,
you can use Calendar object to get the year out. Or even SimpleDateFormat object would work too
etc...
Related
public void searchKlijenta(KlijentiFormEvent klijentiFormEvent) throws SQLException {
String nazivK = klijentiFormEvent.getNaziv();
String adresaK = klijentiFormEvent.getAdresa();
String gradK = klijentiFormEvent.getGrad();
String drzavaK = klijentiFormEvent.getDrzava();
String telefonK = klijentiFormEvent.getTelefon();
String faxK = klijentiFormEvent.getFax();
String mailK = klijentiFormEvent.getMail();
String mobitelK = klijentiFormEvent.getMobitel();
String oibK = klijentiFormEvent.getOib();
String ugovorK = klijentiFormEvent.getUgovor();
String osobaK = klijentiFormEvent.getOsoba();
if (nazivK.length() == 0)
nazivK = null;
if (adresaK.length() == 0)
adresaK = null;
if (gradK.length() == 0)
gradK = null;
if (drzavaK.length() == 0)
drzavaK = null;
if (telefonK.length() == 0)
telefonK = null;
if (faxK.length() == 0)
faxK = null;
if (mailK.length() == 0)
mailK = null;
if (mobitelK.length() == 0)
mobitelK = null;
if (oibK.length() == 0)
oibK = null;
if (ugovorK.length() == 0)
ugovorK = null;
if (osobaK.length() == 0)
osobaK = null;
klijentiSearchModel.clear();
String sql = "select * from zavrsni.klijenti where naziv like '"+nazivK+"' or adresa like '"+adresaK+"' or grad like '"+gradK+"' or drzava like '"+drzavaK+"' or telefon like '"+telefonK+"' or fax like '"+faxK+"' or mail like '"+mailK+"' or mobitel like '"+mobitelK+"' or oib like '"+oibK+"' or ugovor like '"+ugovorK+"' or osoba like '"+osobaK+"' ";
Statement selectStmt = con.createStatement();
ResultSet result = selectStmt.executeQuery(sql);
while(result.next()) {
int id = result.getInt("id");
String naziv = result.getString("naziv");
String adresa = result.getString("adresa");
String grad = result.getString("grad");
int posBr = result.getInt("posBr");
String drzava = result.getString("drzava");
String telefon = result.getString("telefon");
String fax = result.getString("fax");
String mail = result.getString("mail");
String mobitel = result.getString("mobitel");
String oib = result.getString("oib");
String ugovor = result.getString("ugovor");
String osoba = result.getString("osoba");
KlijentiModelSearch klijentSearch = new KlijentiModelSearch(id, naziv, adresa, grad, posBr, drzava, telefon, fax, mail, mobitel, oib, ugovor, osoba);
klijentiSearchModel.add(klijentSearch);
}
result.close();
selectStmt.close();
}
Can i write this code shorter? I think of "if" statement?
Perhaps through a while loop?
Method that is use for search some client in database. This method work fane but this if-statement i want write shorter.
Thanks
EDIT SOLVED:
public void traziKlijenta(KlijentiFormEvent klijentiFormEvent) throws SQLException {
String nazivK = returnNullIfEmptys(klijentiFormEvent.getNaziv());
String adresaK = returnNullIfEmptys(klijentiFormEvent.getAdresa());
String gradK = returnNullIfEmptys(klijentiFormEvent.getGrad());
String drzavaK = returnNullIfEmptys(klijentiFormEvent.getDrzava());
String telefonK = returnNullIfEmptys(klijentiFormEvent.getTelefon());
String faxK = returnNullIfEmptys(klijentiFormEvent.getFax());
String mailK = returnNullIfEmptys(klijentiFormEvent.getMail());
String mobitelK = returnNullIfEmptys(klijentiFormEvent.getMobitel());
String oibK = returnNullIfEmptys(klijentiFormEvent.getOib());
String ugovorK = returnNullIfEmptys(klijentiFormEvent.getUgovor());
String osobaK = returnNullIfEmptys(klijentiFormEvent.getOsoba());
klijentiSearchModel.clear();
String sql = "select * from zavrsni.klijenti where naziv like '%"+nazivK+"%' or adresa like '%"+adresaK+"%' or grad like '%"+gradK+"%' or drzava like '%"+drzavaK+"%' or telefon like '%"+telefonK+"%' or fax like '%"+faxK+"%' or mail like '%"+mailK+"%' or mobitel like '%"+mobitelK+"%' or oib like '%"+oibK+"%' or ugovor like '%"+ugovorK+"%' or osoba like '%"+osobaK+"%' ";
Statement selectStmt = con.createStatement();
ResultSet result = selectStmt.executeQuery(sql);
while(result.next()) {
int id = result.getInt("id");
String naziv = result.getString("naziv");
String adresa = result.getString("adresa");
String grad = result.getString("grad");
int posBr = result.getInt("posBr");
String drzava = result.getString("drzava");
String telefon = result.getString("telefon");
String fax = result.getString("fax");
String mail = result.getString("mail");
String mobitel = result.getString("mobitel");
String oib = result.getString("oib");
String ugovor = result.getString("ugovor");
String osoba = result.getString("osoba");
KlijentiModelSearch klijentSearch = new KlijentiModelSearch(id, naziv, adresa, grad, posBr, drzava, telefon, fax, mail, mobitel, oib, ugovor, osoba);
klijentiSearchModel.add(klijentSearch);
}
result.close();
selectStmt.close();
}
private String returnNullIfEmptys(String value) {
if (value == null || value.length() == 0) {
return null;
}
return value;
}
With your actual code, #khelwood proposition in your comment question is the best approach.
Other solutions have overhead and change your design without bringing a added value .
public static String returnNullIfEmpty(String value){
if (value == null || value.length() == 0){
return null;
}
return value;
}
Then you can call it in this way :
nazivK = returnNullIfEmpty(nazivK);
adresaK= returnNullIfEmpty(adresaK);
EDIT
With the edit of your question, you could include processing as the time where you retrieve the value from the klijentiFormEvent object :
String nazivK = returnNullIfEmpty(klijentiFormEvent.getNaziv());
String adresaK = returnNullIfEmpty(klijentiFormEvent.getAdresa());
...
You simply have to put your arrays/lists ... whatever those things are ... into another array or list.
Then you iterate that array/list.
Done.
And hint: your naming could be improved dramatically. Your names should indicate what the "thing" behind the variable actually is.
Also you can use Map<String, List<?>> to store your lists/arrays/strings. for example with List:
Map<String, List<?>> map = new HashMap<>();
map.put("nazivK", new ArrayList<>());
map.put("adresaK", new ArrayList<>());
//.....
//replace all lists with null
map.replaceAll((s, list) -> list.isEmpty() ? null : list);
//or just remove it
for(Iterator<Map.Entry<String, List<?>>> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, List<?>> entry = it.next();
if(entry.getValue().isEmpty()) {
it.remove();
}
}
As it was suggested by GhostCat, put your values into array/list.
You can do for example something like this (I suppose those values are Strings):
/* Order in array nazivK, adresaK, gradK, drzavaK, telefonK,
faxK, mailK, mobitelK, oibK, ugovorK, osobaK */
String values[] = new String[11];
for (String val: values) {
if (val == null || val.length() == 0) {
val = null;
}
}
Ok, so I'm having some difficulties in returning multiple results on this query in Java
public String getActive() throws SQLException
{
Connection con = DBConnect.getConnection();
String numeUser = "";
String sql=("select NUME from agents WHERE ACTIV = ? AND FILIALA = ? ");
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1, 1);
pstmt.setString(2, "MS10");
ResultSet rs = pstmt.executeQuery();
while(rs.next())
{
numeUser = rs.getString("NUME");
}
rs.close();
con.close();
return numeUser;
}
I heard something about that i can return the result with split() method or tokenizer but I don't seem to return the right result.
Agenti q2 = new Agenti();
String str1 = q2.getActive();
StringTokenizer stk1 = new StringTokenizer(str1);
String[] s1 = new String[0];
int i = 0;
while(stk1.hasMoreElements())
{
s1[i] = (String) stk1.nextElement();
i++;
}
System.out.println(s1[0]);
This is my tokenizer code. Can someone help me a little, please?
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
actually I have 10-30 dummies to get the value from txtCC, but i'd only used 3 dummies for example below..
So how do I get each values and save it directly to my database without using dummy? It's a big deal coz' my code was too large to compile using those dummies..
THANKS for any help..
private void bSaveActionPerformed(java.awt.event.ActionEvent evt)
{
// Save to database
String cc = txtCC.getText();
String delimiter = ",";
String[] temp;
temp = cc.split(delimiter);
for(int i = 0; i < temp.length; i++)
if(i==0) {
txtC1.setText(temp[0]);
txtC2.setText("0");
txtC3.setText("0"); }
else if (i==1) {
txtC1.setText(temp[0]);
txtC2.setText(temp[1]);
txtC3.setText("0"); }
else if (i==2) {
txtC1.setText(temp[0]);
txtC2.setText(temp[1]);
txtC3.setText(temp[2]); }
try {
String cc1 = txtC1.getText(); int CC1 = Integer.parseInt(cc1);
String cc2 = txtC2.getText(); int CC2 = Integer.parseInt(cc2);
String cc3 = txtC3.getText(); int CC3 = Integer.parseInt(cc3);
int opt = JOptionPane.showConfirmDialog(null,"Are you sure you want to save this record? ");
if (opt == 0){
if(!txtC1.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC1);
rs.insertRow();
rs.close();
}
if(!txtC2.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC2);
rs.insertRow();
rs.close();
}
if(!txtC3.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC3);
rs.insertRow();
rs.close();
}
}
}
catch (SQLException err){
JOptionPane.showMessageDialog(FrmEmpLiquidation.this, err.getMessage());
}
}
Instead of using dummies, create simple small methods and make use of it. This will reduce you line of code. and also easy to understand.
private void bSaveActionPerformed(java.awt.event.ActionEvent evt){
// Save to database
String cc = txtCC.getText();
String delimiter = ",";
String[] temp;
temp = cc.split(delimiter);
for(int i = 0; i < temp.length; i++)
insertData(temp[i]);
}
public void insertData(final String data){
txtC1.setText(data);
try {
String cc1 = txtC1.getText(); int CC1 = Integer.parseInt(cc1);
int opt = JOptionPane.showConfirmDialog(null,"Are you sure you want to save this record? ");
if (opt == 0){
if(!txtC1.getText().equals("0")) {
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "Select * from tbl_liqinfo";
rs = stmt.executeQuery(sql);
rs.next();
rs.moveToInsertRow();
rs.updateInt("CC", CC1);
rs.insertRow();
rs.close();
}
}
}
catch (SQLException err){
JOptionPane.showMessageDialog(FrmEmpLiquidation.this, err.getMessage());
}
}
In the below code I am copying resultset content to arraylist. First part of the wile loop i.e while(RS.next()) is returing the results but when cursor moves to
Next while loop i.e while(SR.next()) I am getting "result set is closed". Please help me where I am doing mistake.
String SSQ = "select DISTINCT S_NUMBER from OTG.S_R_VAL" +
" WHERE R_TS = (SELECT MAX(R_TS) FROM OTG.S_R_VAL) order by S_NUMBER";
String SDS = "SELECT DISTINCT S_NUMBER FROM OTG.S_R_VAL AS STG WHERE S_NUMBER NOT IN" +
"(SELECT S_NO FROM OTG.R_VAL AS REV WHERE STG.S_NUMBER = REV.S_NO )";
String SSR = "SELECT DISTINCT S_NO FROM OTG.R_VAL where S_NO != 'NULL' order by S_NO";
String SSO = "Select O_UID from OTG.OPTY where C_S_NO IN" +
"( SELECT DISTINCT S_NUMBER FROM OTG.S_R_VAL AS STG WHERE S_NUMBER NOT IN(SELECT S_NO FROM OTG.R_VAL AS REV WHERE STG.S_NUMBER = REV.S_NO ))";
//Statement statement;
try {
connection = DatabaseConnection.getCon();
statement = connection.createStatement();
statement1 = connection.createStatement();
statement2 = connection.createStatement();
statement3 = connection.createStatement();
statement4 = connection.createStatement();
ResultSet RS = statement1.executeQuery(selectQuery);
ResultSet DS = statement2.executeQuery(Distinct_SiebelNo);
ResultSet SR = statement3.executeQuery(SiebelNo_Rev);
ResultSet SO = statement4.executeQuery(selected_OppId);
ArrayList<String> RSList = new ArrayList<String>();
ArrayList<String> SRList = new ArrayList<String>();
/* ResultSetMetaData resultSetMetaData = RS.getMetaData();
int count = resultSetMetaData.getColumnCount();*/
int count=1;
System.out.println("******count********"+count);
while(RS.next()) {
int i = 1;
count=1;
while(i < count)
{
RSList.add(RS.getString(i++));
}
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
/* ResultSetMetaData resultSetMetaData1 = SR.getMetaData();
int count1 = resultSetMetaData1.getColumnCount();*/
int count1=1;
while(SR.next()) {
int i = 1;
while(i < count1)
{
SRList.add(SR.getString(i++));
}
System.out.println(SR.getString("SIEBEL_NO"));
SRList.add( SR.getString("SIEBEL_NO"));
}SR.close();
connection.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The logic of each loop is flawed.
int count=1;//Count is being set to one
while(RS.next()) {
int i = 1;//i is being set to one
count=1;//count again set to one
while(i < count) //condition will always fail as one is never less than one
{
RSList.add(RS.getString(i++));//Code is never Reached
}
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
The second while is not needed. Just use this:
int count = 1;
while(RS.next()) {
RSList.add(RS.getString(count++));
System.out.println(RS.getString("SIEBEL_NUMBER"));
RSList.add( RS.getString("SIEBEL_NUMBER"));
}
EDIT
int count1=1;
while(SR.next()) {
SRList.add(SR.getString(count1++));
System.out.println(SR.getString("SIEBEL_NO"));
SRList.add( SR.getString("SIEBEL_NO"));
}
EDIT 2:
for (String s : RSList)
for(String s1 : SRList)
if (s.equals(s1))
//Do what you need
You are using the first resultset (RS) in the second loop (System.out.println line)