Runtime Jtree problem - Java Applet Development

I have a database that contains all values and for all my functions I am getting values from it. I need to create Jtree for certain purpose but its too hard to get the Jtree at runtime.. here I have attached part of my program and its not working..Please hep me out on this........
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        String resSet = " where parentid=0 AND SDATA NOT LIKE 'PNL%'";
        try
        {
                    Class.forName("org.apache.derby.jdbc.ClientDriver");
                    Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/D:/SAMPLE DATA/SCOPY;create=true;user=vp;password=rvp");
                    Statement st = conn.createStatement();
                    ResultSet rs = null;
                    rs = st.executeQuery("select * from " + table + resSet);
                    while (rs.next())
                    {
                        parents.clear();
                        parents.add(compOeso.get(rs.getString(2)));
                        findInnerChilds(rs.getString(2));
                    }
        }
        catch(Exception e)
        {
   
        }
          jPanel1.setVisible(true);
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
        String resSet = " where parentid=0 AND SDATA NOT LIKE 'PNL%'";
        try
        {
                    Class.forName("org.apache.derby.jdbc.ClientDriver");
                    Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/D:/SAMPLE DATA/SCOPY;create=true;user=vp;password=rvp");
                    Statement st = conn.createStatement();
                    ResultSet rs = null;
                    rs = st.executeQuery("select * from " + table + resSet);
                    while (rs.next())
                    {
                        parents.clear();
                        parents.add(compOeso.get(rs.getString(2)));
                        findInnerChilds(rs.getString(2));
                    }
        }
        catch(Exception e)
        {
   
        }
          jPanel1.setVisible(true);
}
  private void findInnerChilds(String parent )
    {         
        try
        {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
            Connection conn = DriverManager.getConnection("jdbc:derby://localhost:1527/D:/SAMPLE DATA/SCOPY;create=true;user=vp;password=rvp");
            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery("select * from " + table + " where parentid =(select compid from " + table + " where sdata='" + parent + "')");
            while (rs.next())
            {
//                   DefaultMutableTreeNode root = new DefaultMutableTreeNode(rs.getString(2));
               parents.add(compOeso.get(rs.getString(2)));
                Vector obj = new Vector();
                parents.trimToSize();
                for (int i = 0; i < parents.size()-2; i++)
                {
                     obj.add(parents.get(i));
                         }
                      jTree1 = new javax.swing.JTree(obj);
                      jScrollPane1.setViewportView(jTree1);
}
catch (Exception ex)
        {
            System.out.println("err " + ex.getMessage());
        }
    }Edited by: Jack07 on Aug 25, 2010 1:55 AM 

For better help sooner, post an SSCCE *(<- link).* For the SSCCE, hard code the data coming from the DB.
But while I'm here.
- In broken code, never [swallow exceptions|http://pscode.org/javafaq.html#stacktrace] *(<- link).*
- Explain exactly what ..
for certain purpose but its too hard to get the Jtree at runtime..means. And by that I mean:
1) What behavior did you expect?
2) What actually happens?

Related

unable to build project

Hi all,
I'm using Netbeans IDE 7.3. When i tried to clean and build my project i received the following error:
Note: D:\work\netbeans\snejana_bah\src\myFinance\Categories.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.This class worked fine yesterday and no changes made... Any ideas?
Here is the source:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package myFinance;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
/**
*
* #author Sasho
*/
public class Categories {
//    String host = "jdbc:derby:D:\\sasho\\java_work\\work\\SnejanaBah\\snejana_bah;create=true";
    String host = "jdbc:derby:release\\snejana_bah";
    String uName = "fester";
    String uPass = "fester";
    ResultSet res = null;
    String month = null;
    final DefaultComboBoxModel<DefaultComboBoxModel> model = new DefaultComboBoxModel<DefaultComboBoxModel>();
    String[] comboBoxArray;
    Double limit = 0.0;
    String index;
   
    public String getMonth(Integer mon) {
        switch (mon) {
            case 0:
                month = "Януари";
                break;
            case 1:
                month = "Февруари";
                break;
            case 2:
                month = "Март";
                break;
            case 3:
                month = "Април";
                break;
            case 4:
                month = "Май";
                break;
            case 5:
                month = "Юни";
                break;
            case 6:
                month = "Юли";
                break;
            case 7:
                month = "Август";
                break;
            case 8:
                month = "Септември";
                break;
            case 9:
                month = "Октомври";
                break;
            case 10:
                month = "Ноември";
                break;
            case 11:
                month = "Декември";
                break;
        }
        return month;
    }
    public int getMonthInt(String mon) {
        int montInt = 0;
        switch (mon) {
            case "Януари":
                montInt = 0;
                break;
            case "Февруари":
                montInt = 1;
                break;
            case "Март":
                montInt = 2;
                break;
            case "Април":
                montInt = 3;
                break;
            case "Май":
                montInt = 4;
                break;
            case "Юни":
                montInt = 5;
                break;
            case "Юли":
                montInt = 6;
                break;
            case "Август":
                montInt = 7;
                break;
            case "Септември":
                montInt = 8;
                break;
            case "Октомври":
                montInt = 9;
                break;
            case "Ноември":
                montInt = 10;
                break;
            case "Декември":
                montInt = 11;
                break;
        }
        return montInt;
    }
    public ResultSet getLimits(Integer year, String month, Boolean check) {
        try {
            Connection con = DriverManager.getConnection(host, uName, uPass);
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            if (check) {
                PreparedStatement ps = con.prepareStatement("select l.ID, "
                        + "c.CATEGORY_NAME as Категория, "
                        + "l.LIMIT_YEAR as Година,"
                        + " l.\"MONTH\" as Месец, "
                        + "l.\"LIMIT\" as Лимит "
                        + "from FESTER.LIMITS l , "
                        + "fester.CATEGORIES c\n"
                        + "where l.CAT_ID = c.ID "
                        + "and l.limit_year = ? "
                        + "order by c.CATEGORY_NAME, l.\"MONTH\"");
                ps.setInt(1, year);
                res = ps.executeQuery();
            } else {
                PreparedStatement ps = con.prepareStatement("select l.ID, "
                        + "c.CATEGORY_NAME as Категория, "
                        + "l.LIMIT_YEAR as Година,"
                        + " l.\"MONTH\" as Месец, "
                        + "l.\"LIMIT\" as Лимит "
                        + "from FESTER.LIMITS l , "
                        + "fester.CATEGORIES c\n"
                        + "where l.CAT_ID = c.ID "
                        + "and l.limit_year = ? "
                        + "and l.month = ? "
                        + "order by c.CATEGORY_NAME, l.\"MONTH\"");
                ps.setInt(1, year);
                ps.setString(2, month);
                res = ps.executeQuery();
            }
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(Reports.class.getName()).log(Level.SEVERE, null, ex);
        }
        return res;
    }
    public void insertLimit(Integer cat_id, Integer year, String month, Double limit) {
        try {
            Connection con = DriverManager.getConnection(host, uName, uPass);
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            PreparedStatement stmt = con.prepareStatement("select max(id) + 1 as id from FESTER.LIMITS");
            ResultSet rs = stmt.executeQuery();
            Integer id = null;
            while (rs.next()) {
                id = rs.getInt("ID");
            }
            PreparedStatement ps = con.prepareStatement("insert into FESTER.LIMITS \n"
                    + "values(?,?,?,?,?)");
            ps.setInt(1, id);
            ps.setInt(2, cat_id);
            ps.setInt(3, year);
            ps.setString(4, month);
            ps.setDouble(5, limit);
            ps.executeUpdate();
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(Reports.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void updateLimit(Integer id, Integer year, String month, Double limit) {
        try {
            Connection con = DriverManager.getConnection(host, uName, uPass);
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            PreparedStatement ps = con.prepareStatement("update fester.limits t "
                    + "set t.limit_year = ?, t.month = ?, t.limit = ? "
                    + "where t.id = ?");
            ps.setInt(1, year);
            ps.setString(2, month);
            ps.setDouble(3, limit);
            ps.setInt(4, id);
            ps.executeUpdate();
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(Reports.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void insertCategory(String catName, Integer type, String Desc) {
        try {
            Integer id = 0;
            Connection con = DriverManager.getConnection(host, uName, uPass);
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            PreparedStatement st = con.prepareStatement("select max(id) + 1 as id from fester.categories");
            ResultSet rs = st.executeQuery();
            while (rs.next()) {
                id = rs.getInt("ID");
            }
            PreparedStatement ps = con.prepareStatement("insert into fester.categories values(?,?,?,?)");
            ps.setInt(1, id);
            ps.setString(2, catName);
            ps.setString(3, Desc);
            ps.setInt(4, type);
            ps.executeUpdate();
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(Reports.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void fillCombobox(JComboBox box) {
        try {
            Connection con = DriverManager.getConnection(host, uName, uPass);
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            PreparedStatement ps = con.prepareStatement("select category_name from fester.categories where id <> 0 group by category_name");
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                box.addItem(rs.getObject(1));
            }
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(Reports.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void fillComboboxDebit(JComboBox box) {
        try {
            Connection con = DriverManager.getConnection(host, uName, uPass);
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            PreparedStatement ps = con.prepareStatement("select category_name from fester.categories where id <> 0 "
                    + "and trx_type = 1 "
                    + "group by category_name");
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                box.addItem(rs.getObject(1));
            }
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(Reports.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void fillComboboxCredit(JComboBox box) {
        try {
            Connection con = DriverManager.getConnection(host, uName, uPass);
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            PreparedStatement ps = con.prepareStatement("select category_name from fester.categories where id <> 0 "
                    + "and trx_type = 0 "
                    + "group by category_name");
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                box.addItem(rs.getObject(1));
            }
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(Reports.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
    }
    public Double getCurrentLimit(Integer catId, String month) {
        try {
            Connection con = DriverManager.getConnection(host, uName, uPass);
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            PreparedStatement ps = con.prepareStatement("select limit from fester.limits where cat_id = ? and month = ?");
            ps.setInt(1, catId);
            ps.setString(2, month);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                limit = rs.getDouble("limit");
            }
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(Reports.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
        return limit;
    }
    public Double getTotal(int month, Integer year, Integer catId) {
        try {
            Connection con = DriverManager.getConnection(host, uName, uPass);
            Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
            PreparedStatement ps = con.prepareStatement("select sum(t.AMOUNT) as amnt from fester.TRANSACTIONS t \n"
                    + "where month(t.DATE_CREATED) = ?\n"
                    + "and year(t.DATE_CREATED) = ?\n"
                    + "and t.CATEGORY = ?  ");
            ps.setInt(1, month);
            ps.setInt(2, year);
            ps.setInt(3, catId);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                limit = rs.getDouble("amnt");
            }
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(Reports.class
                    .getName()).log(Level.SEVERE, null, ex);
        }
        return limit;
    }
    public String getLimitIndex(Double total, Double limit) {
        if (total > limit) {
            index = "Отрицателен";
        } else {
            index = "Положителен";
        }
        return index;
}Thanks in advance,
Alexander. 
Before making assumptions that border on the supernatural, do as the Java compiler tells you and find out which lines it has problems with. Than you can easily see what is the truth and what is not. Sometimes IDEs go loopy because for example something fudges up when the project settings are saved during shutdown, but you must first make a case where you have the right to believe that. 
Hi,
Thanks for reply. I believe that the error comes from the line:
final DefaultComboBoxModel<DefaultComboBoxModel> model = new DefaultComboBoxModel<DefaultComboBoxModel>();When i comment the methods using this - i'm able to clean and build the project. Maybe something wrong here with the Generics... I cannot find how to apply this
Recompile with -Xlint:unchecked for detailsAny ideas?
Thanks,
Alexander. 
Doesn't Netbeans underline lines with warnings using yellow? 
Hi,
Thanks for reply.
It does. It's this line:
final DefaultComboBoxModel<DefaultComboBoxModel> model = new DefaultComboBoxModel<DefaultComboBoxModel>();So the hint was to change it to diamond reference and i made it :
final DefaultComboBoxModel<DefaultComboBoxModel> model = new DefaultComboBoxModel <> ();But i still receive the error: Note: D:\work\netbeans\snejana_bah\src\myFinance\Categories.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.Ideas?
Thanks in advance,
Alexander.
Edited by: a.stoyanov on May 16, 2013 5:04 AM 
Due to this editor i'm unable to add html brackets
so after diamond reference it looks like : final DefaultComboBoxModel<DefaultComboBoxModel> model = new DefaultComboBoxModel <html brackets> ();
Edited by: a.stoyanov on May 16, 2013 5:05 AM
Edited by: a.stoyanov on May 16, 2013 5:05 AM 
Tolls wrote:
Doesn't Netbeans underline lines with warnings using yellow?It does, unless you turn it off.
DefaultComboBoxModel<DefaultComboBoxModel>Quite odd to see the class itself in the generic type definition.
Also get the terminology straight: you are not getting errors, you are getting warnings. 
So... the class can be build with this warning and if i run the project from the IDE it's working fine... But if i start the jar file from the DIST folder - it doesn't. The methods from this class are not used.
The purpose of this class is to fill comboboxes and i refer to it in the init components. So, when the project is being started - the comboboxes are empty... 
I checked the -Xlint:unchecked option in my IDE
and here is the warning message:
D:\work\netbeans\snejana_bah\src\myFinance\Categories.java:301: warning: [unchecked] unchecked call to addItem(E) as a member of the raw type JComboBox
                box.addItem(rs.getObject(1));
  where E is a type-variable:
    E extends Object declared in class JComboBox
D:\work\netbeans\snejana_bah\src\myFinance\Categories.java:335: warning: [unchecked] unchecked call to addItem(E) as a member of the raw type JComboBox
                box.addItem(rs.getObject(1));
  where E is a type-variable:
    E extends Object declared in class JComboBox
D:\work\netbeans\snejana_bah\src\myFinance\Categories.java:366: warning: [unchecked] unchecked call to addItem(E) as a member of the raw type JComboBox
                box.addItem(rs.getObject(1));
  where E is a type-variable:
    E extends Object declared in class JComboBox
3 warningsAlexander. 
This borders on being outside my area of expertise, but why do you have new X<X>() instead of new X() ? This seems an exceedingly odd design and might be confusing the compiler. Perhaps a redesign is in order?

Searching from the database.

Can any one give me the code for searching from the database using J2se 1.5?
or the sql query which I can apply in my coding. 
Goooooogle 
will this is a part of code i used with one of my programs..
it's a hotel program and i was checking if the room is rented or not, by getting a column from the DB called rented_or_not which can take one of two values (true, false)...
so here's the snap code:
Connection connection = null;
public static void connectToDatabase(){
        try {
            DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
            connection = DriverManager.getConnection(DATABASE_URL,"DBUserName","DBPassword");
            connection.setAutoCommit(false);
        }
        catch (SQLException e) {
            System.err.println("SQLException During Connecting Happened");
        }
}this is just how to connect the DB...
and then how to use SQL queries here's the method i used:
public boolean checkRoomReservedOrNot(int room_id){
        Statement statement = null;
       
        try{
            statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("SELECT rented_or_not FROM rooms WHERE room_id = "+ room_id);
            resultSet.next();
            String rented_or_not = resultSet.getString(1);
            if(rented_or_not.equals("TRUE"))
                return true;
            else
                return false;
           
        }
        catch (SQLException e) {
            System.err.println("SQL Exception in checkRoomReservedOrNot");
        }
        return false;
}hope it helps..
Q.Najjar (^_^); 
Look at this part of my code, you may find it interesting"
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
       
    
        driver();
       
        try {
           
            Connection conn = DriverManager.getConnection(url);
            Statement stmt = conn.createStatement();
            String field1;
            char[] field2;
           
            field1=jTextField1.getText();
            field2=jPasswordField1.getPassword();
            ResultSet r=stmt.executeQuery("select user,password from users_data");
           
            String user,password;
            user="u";
            password="p";
            int incre=0;
           
             while (r.next())
            {user= r.getString(1);
             password= r.getString(2);
            
              if ( user.compareTo(field1)==0&password.compareTo(String.valueOf(field2))==0) {
                    javax.swing.JOptionPane.showMessageDialog(null, "welcome...!",
                      "Authenticating..", javax.swing.JOptionPane.INFORMATION_MESSAGE);
                      incre+=1;    
                }
            }
                 
            if (incre==0)
                {
            javax.swing.JOptionPane.showMessageDialog(null, "no username or password exists",
                      "Authenticating...", javax.swing.JOptionPane.ERROR_MESSAGE);
            }
                     
        } catch (Exception e) {
            javax.swing.JOptionPane.showMessageDialog(null, e.getMessage(),
                    "Database Error", javax.swing.JOptionPane.INFORMATION_MESSAGE);
        }
    }

All threads currently busy - tomcat/servlet prob

Hi,
Not sure if this is the correct place to post this message, but do not know where else to post.
There is a servlet being called from an automation host (Update_Toolcounts).
After running for some period of time (about a day), tomcat locks-up and generates error -
"SEVERE:all threads (150) are currently busy" Any ideas on where to go from here would be greatly appreciated.
//package GLOK;
import java.io.IOException;
import java.sql.*;
import java.util.*;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Update_Toolcounts extends HttpServlet
{
    public Update_Toolcounts()
    {
    }
    public void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException
    {
     
        Statement myStatement = null;
        Map parameters = req.getParameterMap();
        Iterator i = parameters.keySet().iterator();
        int qtyVars = parameters.size();
        String varName[] = new String[qtyVars];
        String varval[] = new String[qtyVars];
        int ii = 0;
        res.setContentType("text/html");
        java.io.PrintWriter out = res.getWriter();
        try
        {
            //TPMCDEV Connection__________________________________
            Connection conn = Custom.cn_Mgr("lookup", "java:comp/env/jdbc/myTPMCENTER");
            //____________________________________________________
           
            myStatement = conn.createStatement();
            ResultSet rs = myStatement.executeQuery("SELECT user, sysdate FROM dual");
            rs.next();
            java.sql.Timestamp CurrDateTime = rs.getTimestamp("sysdate");
            String toolStr[] = (String[])parameters.get("Tool");
            String tool = toolStr[0];
            String typeStr[] = (String[])parameters.get("Type");
            String Type = typeStr[0];
 
           
            if(Type.equals("CUM_CNT"))
            {
                do
                {
                    if(!i.hasNext())
                        break;
                    String param = (String)i.next();
                    if(!param.equals("Tool") || !param.equals("Type"))
                    {
                        String paramValStr[] = (String[])parameters.get(param);
                        String paramVal = paramValStr[0];
                        varName[ii] = param;
                        varval[ii] = paramVal;
                        ii++;
                    }
                } while(true);
                Update_Cumulative_Ctrl(conn, tool, varName, varval);
               
            } else
            {
               
                String aux1Str[] = (String[])parameters.get("AUX1");
                String aux1 = aux1Str[0];
                String aux7Str[] = (String[])parameters.get("AUX7");
                String aux7 = aux7Str[0];
                Update_Incremental_Ctrl(conn, tool, Type, aux1, aux7);
            }
            rs.close();
           
            Validate_Stack_Update(conn, tool);
           
            myStatement.close();
            conn.close();
        }
       
        catch(SQLException e) { }
        catch(NamingException e) { }
        catch(Exception e) { }
       
    }
    public static void Update_Cumulative_Ctrl(Connection conn, String tool, String allVars[], String allVals[])
    {
        Statement myStatement = null;
        try
        {
            myStatement = conn.createStatement();
            for(int i = 0; i < allVars.length; i++)
            {
                myStatement = conn.createStatement();
                ResultSet MyResultSet2 = myStatement.executeQuery("UPDATE GLOK_COUNTS SET ITEM_VALUE = '" + allVals[i] + "'" + ",  DATE_TIME = sysdate  WHERE TOOL = '" + tool + "' AND ITEM = '" + allVars[i] + "'");
            }
            myStatement.close();
        }
        catch(SQLException e) { }
    }
    public static String Update_Incremental_Ctrl(Connection conn, String tool, String Type, String aux1, String aux7)
    {
        Statement myStatement = null;
        String myOut = null;
        try
        {
          
            myStatement = conn.createStatement();
            int i = 0;
           
            String myVal;
            if(aux7.equals("AUTO"))
                myVal = "0";
            else
            if((aux7.trim()).equals("WFR"))
          
            {
                myVal = aux1;
                myStatement.executeQuery("INSERT INTO GLOK_INC_RAWCNT (DATE_TIME, TOOL, ITEM, ITEM_VALUE) VALUES(sysdate, '" + tool + "', 'WFR:', '" + myVal + "')");
                myStatement.executeQuery("UPDATE GLOK_COUNTS SET ITEM_VALUE = (ITEM_VALUE + '" + myVal + "') WHERE TOOL = '" + tool + "' AND ITEM = '" + aux7.substring(0,3) + ":'");
            } else
            if(aux7.substring(0, 3).equals("RUN"))
            {
                myVal = "1";
                myStatement.executeQuery("INSERT INTO GLOK_INC_RAWCNT (DATE_TIME, TOOL, ITEM, ITEM_VALUE) VALUES(sysdate, '" + tool + "', 'RUN:', '1')");
                myStatement.executeQuery("UPDATE GLOK_COUNTS SET ITEM_VALUE = (ITEM_VALUE + '" + myVal + "') WHERE TOOL = '" + tool + "' AND ITEM = '" + aux7.substring(0,3) + ":'");
            } else
            if(aux7.substring(0, 4).equals("RCPX"))
            {
                myVal = aux7.substring(5, aux7.length());
                myStatement.executeQuery("INSERT INTO GLOK_INC_RAWCNT (DATE_TIME, TOOL, ITEM, ITEM_VALUE) VALUES(sysdate, '" + tool + "', 'RCPX:', '" + myVal + "')");
                myStatement.executeQuery("UPDATE GLOK_COUNTS SET ITEM_VALUE = (ITEM_VALUE + '" + myVal + "') WHERE TOOL = '" + tool + "' AND ITEM = '" + aux7.substring(0,4) + ":'");
            }
            myStatement.close();
        }
               
        catch(SQLException e) {System.out.println(e); }
        return myOut;
    }
   
    public static void Update_Counter_Value_Tbl(Connection conn, String tool, String allVars[]){
        /*
        Statement myStatement = null;
        int i = 0;
        
        ResultSet rs = myStatement.executeQuery("SELECT DISTINCT RESOLUTION FROM GLOK_COUNTS WHERE TOOL = '" + tool + "' ORDER BY RESOLUTION DESC");
        int resolution = rs.getInt("RESOLUTION");
        int diff = resolution/24;
       
        ResultSet rs2 = myStatement.executeQuery("SELECT * FROM GLOK_COUNTS WHERE TOOL = '" + tool + "' AND ITEM = '" + allVars[i] + "'");
       */
       
    }
   
   
    public static void Validate_Stack_Update(Connection conn, String tool){
        Statement myStatement = null;
        String limit;
        int serie_id = 0;
        try
        {
            myStatement = conn.createStatement();
                ResultSet rs = myStatement.executeQuery("SELECT * FROM GLOK_WSOOVERLIMINFO WHERE TOOL = '" + tool + "'");
               
                while(rs.next()){
                    serie_id = rs.getInt("PM_SERIE_ID");
                }
               
                if(serie_id > 1){
                    myStatement.executeQuery("CALL STACK_UPDATE()"); 
                };
               
                if(serie_id <= 1){
                  //  myStatement.executeQuery("INSERT INTO TESTTBL(ACTION,STATUS,TOOL,REMARK)      VALUES('STACK VALIDATION','NO UPDATE', " + tool + ",'none')");
                };               
                               
                myStatement.close();
        }
        catch(SQLException e) { }
         
    } 
You are probably opening resources that are never being closed. Like database connections and io streams.
I noticed you catch a bunch of exceptions all over you app and never do anything with them. The problem with
this is that if any problem occurs in your app, you will have no clue. Also, you close the resources inside the
same try blocks that throw the hidden exceptions. I would suggest moving those closes to a finally block. As they
are, if you get an error (which you don't see 'cause you hide them) your connections won't close.
Connection conn = null;
Statement myStatement;
ResultSet rs = null;
try
{
  //open connection, do sql, don't close connection
}
catch(SQLException e)
{  e.printStackTrace(); }
catch(NamingException e)
{ e.printStackTrace(); }
catch(Exception e)  //Not always a good idea to catch the general exception
{ e.printStackTrace();  }
finally
{
  if (rs != null) try { rs.close(); } catch (Exception e) {}
  if (myStatement != null) try { myStatement.close(); } catch (Exception e) {}
  if (conn != null) try { conn.close(); } catch (Exception e) {}
}
out.close(); //don't forget to close the PrintWriterThen check your logs and/System out to see if errors occur.
The finally block will run wether the try block is completed normally, or if an exception is thrown and caught by the catch blocks. It is the only place to put your resource closures an be sure that they run. 
Thanks for your input, I will adjust my code and see if this resolves the problem. 
what does this do?
do{
     if(!i.hasNext())
          break;
     String param = (String)i.next();
     if(!param.equals("Tool") || !param.equals("Type")){
          String paramValStr[] = (String[])parameters.get(param);
          String paramVal = paramValStr[0];
          varName[ii] = param;
          varval[ii] = paramVal;
          ii++;
     }
}
while(true);you never write aything back
res.setContentType("text/html");
java.io.PrintWriter out = res.getWriter(); 
ref: above part1 I didn't see break
ref: stevejukes post
http://jakarta.apache.org/tomcat/tomcat-5.0-doc/jndi-datasource-examples-howto.html#Common%20Problems
note
     Connection conn = null;
     Statement myStatement;
     ResultSet rs = null;
     try{ 
          // open connection, do sql, >>>don't close connection<<<
          // do close conection and set it to null
          // if you don't you wouldn't catch exception thrown by
          // close operation
          conn.close();
          conn = null
          myStatement.close();
          myStatement = null;
          rs.close();
          rs = null;
     }
     catch(SQLException e) { 
          e.printStackTrace();
     }
     catch(NamingException e) {
           e.printStackTrace();
     }
     catch(Exception e)  //Not always a good idea to catch the general exception{
          e.printStackTrace(); 
     }
     finally{ 
          if (rs != null)
               try {
                    rs.close();
               }
               catch (Exception e) {
               } 
          if (myStatement != null)
               try {
                    myStatement.close();
               }
               catch (Exception e) {
               } 
          if (conn != null)
               try {
                    conn.close();
               }
               catch (Exception e) {
               }
     }
     out.close(); //don't forget to close the PrintWriter
//do close conection and set it to null
// if you don't you wouldn't catch exception thrown by
// close operation
The problem they discuss in the link is if you close it in both the try and finally block without checking for null in the finally. In the example I gave you would only close in the finally. Thread 2 won't get the same DBConnection (it will get a different one from the pool) because the first one was not released. I would not imagine there would be a great deal of difference putting it in the finally only, as far as keeping hold of it for much longer and depleting resources. But that might depend on your system (moving money, or just displaying a BLOG, for example...)
But you do have a point, if you want to report errors that occur in the close method, put it in the try like declangallagher suggests. I consider the close operations a trivial matter (in any problem area I work in. Of course you could believe differently). If I wanted to report any problem with the close I could put it in the catch statements inside my finally block:
   finally{ 
          if (rs != null)
               try {
                    rs.close();
               }
               catch (Exception e) {
                 e.printStackTrace();
               } 
          if (myStatement != null)
               try {
                    myStatement.close();
               }
               catch (Exception e) {
                 e.printStackTrace();
               } 
          if (conn != null)
               try {
                    conn.close();
               }
               catch (Exception e) {
                 e.printStackTrace();
               }
     } 
Thank you for your input, this was all good info.
Regarding the question about this code....
The input string looks something like this
Sending GET /CF6_TPMC_GLOK/Update_Toolcounts?Tool=LAM9611&Type=CUM_CNT&RF=285.87 HTTP/1.0
from the automation host
Tool, and Type are always expected, so are set as variables tool, and type respectively.
This loop states to ignore input equal to "Type" and "Tool" since they are already set.
The remainder of the string following may have unlimited number of input variables which are read into
VarName[ii] and VarVal[ii] and continue setting parameters until there are no more.
if(Type.equals("CUM_CNT"))
            {
                do
                {
                    if(!i.hasNext())
                        break;
                    String param = (String)i.next();
                    if(!param.equals("Tool") || !param.equals("Type"))
                    {
                        String paramValStr[] = (String[])parameters.get(param);
                        String paramVal = paramValStr[0];
                        VarName[ii] = param;
                        VarVal[ii] = paramVal;
                        ii++;
                    }
                } while(true);
                Update_Cumulative_Ctrl(conn, tool, VarName, VarVal);
               
            } else
do{                   
     if(!i.hasNext())                       
          break;                   
     String param = (String)i.next();                   
     if(!param.equals("Tool") || !param.equals("Type")){
          String paramValStr[] = (String[])parameters.get(param);                       
          String paramVal = paramValStr[0];                       
          VarName[ii] = param;
          VarVal[ii] = paramVal;
          ii++;
     }
}
while(true);i didn't see the break when i first looked at this, and thought it was a
problem
do{
}
while(true)never exits
why not
while(i.hasNext()){                   
     String param = (String)i.next();                   
     if(!param.equals("Tool") || !param.equals("Type")){
          String paramValStr[] = (String[])parameters.get(param);                       
          String paramVal = paramValStr[0];                       
          VarName[ii] = param;
          VarVal[ii] = paramVal;
          ii++;
     }
}

How to execute queries in a for loop

Ok, here is the problem. I have a database which contains web page content. When you start the program, the user types in a string and that string is split up into its separate words and stored in a list. Then you are asked for the logic, such as exact, all, or any. I didn't put any in the code yet, so don't worry about that one. exact is simple, I query the pageContent for that word and I print out all rows that were found with the string that was entered. all is easy with just one word, but lets say I have the string "how are you". The tokenizer would store three words in the list which is a String[]. Now for all, in order for the user to get back any results, all of the words, not in the order have to be found in the pageContent, but I can't figure out how to do this. Basically, I'm looking for a way to query the database using AND this case in some kind of loop. The code below should clear somethings up:
import java.io.*;
import java.sql.*;
import java.util.*;
public class simpleTest {
    public static void main(String[] args) throws IOException {
            int rows = 0;
            int count = 0;
            String[] wordList = new String[50];
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
      
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (Exception ex) {System.out.println("No driver");}
     try {
            Connection conn =
          DriverManager.getConnection("jdbc:mysql://localhost/cop4610webs",
          "root", "anatoly");
         
            // Do something with the Connection
         
            System.out.println("Enter a string: ");           
            String word = reader.readLine();
            StringTokenizer words = new StringTokenizer(word);
      
            while(words.hasMoreTokens())
               wordList[count++] = words.nextToken();
        
           
            System.out.println("Enter the logic");
            String logic = reader.readLine();
            Statement stmt = null;
         ResultSet rs = null;
        
             stmt = conn.createStatement();
     
            if(logic.equalsIgnoreCase("exact"))
                {
             rs = stmt.executeQuery("SELECT pageName FROM pages WHERE pageContent ='"+word+"'");
             ResultSetMetaData metaData = rs.getMetaData();
 
             System.out.println("Results of SELECT");
            rs.last(); //move to last row
            rows = rs.getRow(); //check rows returned
            System.out.println(rows);
            rs.beforeFirst(); //move back to beginning
           
            if(rows != 0)
            {
            rs.next();
             System.out.println(rs.getObject(1) );
            while ( rs.next() ) {
               System.out.println(rs.getObject(1) );
         }
            }
            }
            else
                  if(logic.equalsIgnoreCase("all"))
                {
            
                rs = stmt.executeQuery("SELECT pageName FROM pages WHERE pageContent ='"+word+"'");
 
             System.out.println("Results of SELECT");
            rs.last(); //move to last row
            rows = rs.getRow(); //check rows returned
            System.out.println(rows);
            rs.beforeFirst(); //move back to beginning
           
            if(rows != 0)
            {
            rs.next();
             System.out.println(rs.getObject(1) );
            while ( rs.next() ) {
               System.out.println(rs.getObject(1) );
         }
            }
                  }
            rs.close();
           
           
             } catch (SQLException ex) { // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
            System.out.println("VendorError: " + ex.getErrorCode());
        }
    }     
} 
Works towards getting a sql statement something like this:
SELECT pageName FROM pages WHERE pageContent LIKE '%word1%' AND pageContent LIKE '%word2%' AND pageContent LIKE '%word3%';

Connection to Database Error

I am using Oracle Express Edition to work with a project. I have the following code to connect to my database:  
  public static void main(String[] args) {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:driver_type:[username/password]#//host_name:port_number:SID");
            Statement st = con.createStatement();
            ResultSet rs = st.executeQuery("Select * from [Sheet1$]");
            ResultSetMetaData rsmd = rs.getMetaData();
            int numberOfColumns = rsmd.getColumnCount();
           
           
            while (rs.next()) {
                for (int i = 1; i <= numberOfColumns; i++) {
                    if (i > 1)
                        System.out.print(", ");
                    String columnValue = rs.getString(i);
                    System.out.print(columnValue);
                }
                System.out.println("");
            }
            st.close();
            con.close();
        } catch (Exception ex) {
            System.err.print("Exception: ");
            System.err.println(ex.getMessage());
        }
       
      
       
    }
  When I try to run it, I get a failed to call database error, Missing in or out parameter at index 1. What is wrong with my code? Any help would be appreciated.
Hi, can try with this operation:{  Class.forName ("oracle.jdbc.OracleDriver");   Connection conn = DriverManager.getConnection   ("jdbc:oracle:thin:#//localhost:1521/orcl", "brunors", "mypass");I think this hope you : JDBC - Oracle FAQOracleDriver (Oracle Database JDBC Java API Reference) Hugs, Bruno Reis.

Categories

Resources