Please help getString()

hi,
this might sound like a question that shouln't have been asked but
i'm new to java, studied it for a few months (haven't learnt any kind of programming languages before )and been assigned to do a project, tried my best at it but got stuck on this GetString() method
what's wrong with this code
i tried to compile it but came up with errors
cannot find symbol
symbol : method getString()
location: class java.lang.String
stm.setString(4,strdate.getString());
cannot find symbol
symbol : method strtimegetString()
location: class javaproject
stm.setString(5, strtimegetString());
2 errors
here's the code
//javaproject.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.sql.*;
public class javaproject extends JApplet implements ActionListener,Runnable
JPanel panel; JLabel lname, lcode,lterm,ltime,ldate;
JTextField tfname , tfcode;
JButton bttsaved, bttcancel, bttclose;
JComboBox cbterm;     
String term[] ={"Semester A","Semester B","Semester C","Semester D"};
String strdate, strtime ;
Thread time;
GregorianCalendar calendar;
public void init()
     panel = new JPanel();
     lcode = new JLabel ("Code : ");
     lname = new JLabel("Name : ");
     lterm = new JLabel("Term : ");
     ltime = new JLabel();
     ldate = new JLabel();
     tfcode = new JTextField(20);
     tfname = new JTextField(20);
     cbterm = new JComboBox(term);
bttsaved = new JButton(" Saved ");
bttcancel = new JButton(" Cancel ");
bttclose = new JButton(" Close ");
     calendar = new GregorianCalendar();
     time =new Thread(this);
     time.start();
     display();
     panel.add(ldate); panel.add(ltime);
     panel.add(lcode); panel.add(tfcode);
     panel.add(lname); panel.add(tfname);
     panel.add(lterm); panel.add(cbterm);
     panel.add(bttsaved); panel.add(bttcancel); panel.add(bttclose);
     getContentPane().add(panel);
     bttsaved.addActionListener(this);
     bttcancel.addActionListener(this);
     bttclose.addActionListener(this);
public void run()
     for(;;)
     calendar = new GregorianCalendar();
          strtime = calendar.get(Calendar.HOUR)+":"+calendar.get(Calendar.MINUTE)
          +":"+calendar.get(Calendar.SECOND);
          ltime.setText(strtime);
          try
          time.sleep(1000);
          catch(InterruptedException e)
          showStatus("ThreadInterrupted");          
public void display()
     strdate = calendar.get(Calendar.DATE) + "/" + (calendar.get(Calendar.MONTH)+1) + "/"+calendar.get(Calendar.YEAR);
     ldate.setText(strdate);
public void actionPerformed(ActionEvent evt)
     if(evt.getSource() == bttcancel )
     tfcode.setText(" ");
     tfname.setText(" ");
     showStatus(" ..... Please enter new information ..... ");
     if(evt.getSource() == bttclose )
     System.exit(0);          
     if(evt.getSource() ==bttsaved )
     try
          String blankcode = tfcode.getText();
          if(blankcode.length() == 0)
               showStatus("Student's code cannot be empty");
               return;          
          String blankname = tfname.getText();
          if(blankname.length() == 0)
               showStatus("..... Student's name cannot be empty ......");
          return;
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          Connection con;
          con = DriverManager.getConnection("jdbc:odbc:kayteej","sa", null);
          PreparedStatement stm;
          stm = con.prepareStatement("insert into Students values(?,?,?)");
          stm.setString(1,tfcode.getText());     
          stm.setString(2,tfname.getText());
          stm.setString(3,(String)cbterm.getSelectedItem());
          stm.setString(4,strdate.getString());
          stm.setString(5, strtimegetString());
          stm.executeUpdate();     
          showStatus("..... Please enter new information ..... ");
          JOptionPane.showMessageDialog(null, "Data Saved","Congrats!!",1);
     catch(Exception err)
          showStatus("Error occured while interacting with sql");
//<Applet code="javaproject.class" width=800 height=600></applet>
should i use the getString method or is it possible to use other type of methods. please help I'm really stuck
Thank you in advance

So when you run it, the code throws an exception? Then there's something wrong with your code, or with your setup.
The exception's stack trace contains useful information which would help you (or us) figure out just what is wrong. Hopefully you have a catch-block that calls the printStackTrace() method of the exception.

Similar Messages

  • Getting Error:closing a connection for you. Please help

    Hello All,
    I'm using jboss3.2.6. I used ejb2.1 (session bean and entity bean[BMP]). I did few data base transations in cmp and few in simple data source connection.
    I'm getting below errors occasionally
    'No managed connection exception
    java.lang.OutOfMemoryError: Java heap space
    [CachedConnectionManager] Closing a connection for you. Plea
    se close them yourself: org.jboss.resource.adapter.jdbc.WrappedConnection@11ed0d
    5
    I've given below my dao connection code here,
    package com.drtrack.util;
    import java.sql.Connection;
    import java.sql.SQLException;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.sql.DataSource;
    public class DAOUtil {
    private static DataSource _ds;
    public Connection con;
    public DAOUtil() throws SQLException {
    try {
    if (_ds == null)
    assemble();
    if(_ds != null && con == null) {
    con = _ds.getConnection();
    }catch(SQLException ex) {
    ex.printStackTrace();
    private void assemble() {
    Context ic = null;
    try {
    ic = new InitialContext();
    DrTrackUtil drutil = new DrTrackUtil();
    _ds = (DataSource) ic.lookup("java:/" + drutil.getText("SOURCE_DIR"));
    drutil = null;
    }catch (Exception e) {
    e.printStackTrace();
    }finally {
    try {
    ic.close();
    }catch(NamingException ne) {}
    public void closeConnection() throws SQLException {
    if(con != null)
    con.close();
    con = null;
    }below is the code with get connection and doing transaction in it.
    public static AccountMasterValueBean getAccountMasterByAcctId(String acctId) {
    AccountMasterValueBean bean = null;
    DAOUtil dao = null;
    CallableStatement cst = null;
    ResultSet rs = null;
    try {
    dao = new DAOUtil();
    cst = dao.con.prepareCall(DrTrackConstants.MSSQL_USP_ACCOUNTMASTER_BY_ACCTID);
    cst.setObject(1, acctId);
    rs = cst.executeQuery();
    if(rs != null && rs.next()) {
    bean = new AccountMasterValueBean(
    Integer.valueOf(rs.getString("accountkeyid")),
    rs.getString("latitude"),
    rs.getString("longitude"));
    }catch(SQLException se) {
    logger.info("SQL Error: " + se);
    finally {
    if(rs != null){
    try {
    rs.close();
    }catch(SQLException se) {
    logger.info("SQL Error: " + se);
    finally {
    rs = null;
    if(cst != null) {
    try{
    cst.close();
    }catch(SQLException se) {
    logger.info("SQL Error: " + se);
    finally {
    cst = null;
    if(dao != null) {
    try {
    dao.closeConnection();
    }catch(SQLException se) {
    logger.info("SQL Error: " + se);
    finally {
    dao = null;
    return bean;
    }I closed connections, resultsets and statements properly.
    Why I'm getting these errors.? Where I'm doing wrong. ? Please help me. I have to fix them ASAP.
    Thanks.

    Hello All,
    I'm using jboss3.2.6. I used ejb2.1 (session bean and entity bean[BMP]). I did few data base transations in cmp and few in simple data source connection.
    I'm getting below errors occasionally
    'No managed connection exception
    java.lang.OutOfMemoryError: Java heap space
    [CachedConnectionManager] Closing a connection for you. Plea
    se close them yourself: org.jboss.resource.adapter.jdbc.WrappedConnection@11ed0d
    5
    I've given below my dao connection code here,
    package com.drtrack.util;
    import java.sql.Connection;
    import java.sql.SQLException;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.sql.DataSource;
    public class DAOUtil {
    private static DataSource _ds;
    public Connection con;
    public DAOUtil() throws SQLException {
    try {
    if (_ds == null)
    assemble();
    if(_ds != null && con == null) {
    con = _ds.getConnection();
    }catch(SQLException ex) {
    ex.printStackTrace();
    private void assemble() {
    Context ic = null;
    try {
    ic = new InitialContext();
    DrTrackUtil drutil = new DrTrackUtil();
    _ds = (DataSource) ic.lookup("java:/" + drutil.getText("SOURCE_DIR"));
    drutil = null;
    }catch (Exception e) {
    e.printStackTrace();
    }finally {
    try {
    ic.close();
    }catch(NamingException ne) {}
    public void closeConnection() throws SQLException {
    if(con != null)
    con.close();
    con = null;
    }below is the code with get connection and doing transaction in it.
    public static AccountMasterValueBean getAccountMasterByAcctId(String acctId) {
    AccountMasterValueBean bean = null;
    DAOUtil dao = null;
    CallableStatement cst = null;
    ResultSet rs = null;
    try {
    dao = new DAOUtil();
    cst = dao.con.prepareCall(DrTrackConstants.MSSQL_USP_ACCOUNTMASTER_BY_ACCTID);
    cst.setObject(1, acctId);
    rs = cst.executeQuery();
    if(rs != null && rs.next()) {
    bean = new AccountMasterValueBean(
    Integer.valueOf(rs.getString("accountkeyid")),
    rs.getString("latitude"),
    rs.getString("longitude"));
    }catch(SQLException se) {
    logger.info("SQL Error: " + se);
    finally {
    if(rs != null){
    try {
    rs.close();
    }catch(SQLException se) {
    logger.info("SQL Error: " + se);
    finally {
    rs = null;
    if(cst != null) {
    try{
    cst.close();
    }catch(SQLException se) {
    logger.info("SQL Error: " + se);
    finally {
    cst = null;
    if(dao != null) {
    try {
    dao.closeConnection();
    }catch(SQLException se) {
    logger.info("SQL Error: " + se);
    finally {
    dao = null;
    return bean;
    }I closed connections, resultsets and statements properly.
    Why I'm getting these errors.? Where I'm doing wrong. ? Please help me. I have to fix them ASAP.
    Thanks.

  • Please help with my helper class

    Hi,
    plz I need some assistance with this:
    I have a big table which consist of 200 columns. This table gets fields from different tables. It has records of orders which may have several items and each item can have up to 8 taxes. So i have fields reaping for other order order records. I need to display an order then have a navigation to list items in details, with all its taxes, one by one.
    Here is how I have decided to do it in a nutshell. I have decided to get all taxes of a particular item and put in a map with tax_codes as values and tax details arraylist as values. I then add this to an item with its other details. then I add items to a particular order. I have separated orders,items and taxes in their separate beans. Im trying to first the implimentation for each order, item and taxes by displaying them on a JSP. However am currently getting the following error with taxdetails:
    java.lang.ClassCastException: OrderItems.ItemTax cannot be cast to java.lang.String
    at OrderItems.OrderDetails.getItemTaxDetails(OrderDetails.java:166)
    at OrderItems.Controller.processRequest(Controller.java:57)
    at OrderItems.Controller.doGet(Controller.java:72)
    I have a list of all itemTaxCodes am iterating and am casting to string...am not casting ItemTax object.Here is my code below:
    OrderDetails.java
    package orderitems;
    import java.sql.*;
    import java.util.*;
    public class OrderDetails {
        private LineOder lineOrder;
        private Map lineItems;
        //returns an item number, key_item, from its unique keys
        public int getItemNumber(int key_item, String key_year,
                String key_office,String key_client,String key_company){
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            int itmNum = 0;
             * key_item a unique number for an item.
             * key_year,key_office,key_client,key_company unique keys
             * for each order where this key_item is taken
             * from.
            String select = "SELECT key_item FROM "+
                    Constants.WEB_TABLE +" WHERE key_item = " + key_item +
                    " AND key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company +"'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                if(rst.next()){
                    itmNum = Integer.parseInt(rst.getString("key_item"));
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return itmNum;
        //get a list of item number(item codes)
        public List getAllItemNumbers(String key_year,
                String key_office,String key_client,String key_company){
            List itemNumbers = new ArrayList();
            LineItem itemNumber = null;
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            String select = "SELECT key_item FROM "+ Constants.WEB_TABLE +
                    " WHERE key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company + "'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                while(rst.next()){
                    itemNumber = new LineItem();
                    itemNumber.setKey_item(Integer.parseInt(rst.getString("key_item")));
                    itemNumbers.add(itemNumber);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return itemNumbers;
        //get a list of tax codes
        public List getAllTaxCodes(int key_item, String key_year,
                String key_office,String key_client,String key_company){
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            ItemTax taxCode;
            List taxCodes = new ArrayList();
            int itemNum = getItemNumber(key_item, key_year,
                    key_office,key_client,key_company);
            String select = "SELECT key_tax_code FROM "+
                    Constants.WEB_TABLE +" WHERE key_item = " + itemNum +
                    " AND key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company +"'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                while(rst.next()){
                    taxCode = new ItemTax();
                    taxCode.setKey_tax_code(rst.getString("key_tax_code"));
                    taxCodes.add(taxCode);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return taxCodes;
        //use tax code to get tax details
        public Map getItemTaxDetails(String key_year,String key_office,
                String key_client,String key_company,int key_item){
            ItemTax taxDetail = null;
            List taxDetails = new ArrayList();
            List itemTaxCodes = new ArrayList();
            Map itemTaxdetails = new HashMap();
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            //get a list of all tax codes of an item with a
            //given item number
            itemTaxCodes = getAllTaxCodes(key_item,key_year,///a list of tax codes
                    key_office,key_client,key_company);
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                for(Iterator taxCodeIter= itemTaxCodes.iterator(); taxCodeIter.hasNext();){
                    String taxCode = (String)taxCodeIter.next();/////casting taxtCode to string***exception occurs from here
                    String select = "SELECT tax_type,tax_value," +
                            "tax_limit_val FROM "+ Constants.WEB_TABLE +
                            " WHERE key_item = "+ key_item +
                            " AND key_year = '" + key_year + "'" +
                            " AND key_office = '" + key_office + "'" +
                            " AND key_client = '" + key_client + "'" +
                            " AND key_company = '" + key_company +"'" +
                            " AND key_tax_code = '" + taxCode + "'";///tax code string
                    rst = stat.executeQuery(select);
                    while(rst.next()){
                        taxDetail = new ItemTax();
                        //records to be displayed only
                        taxDetail.setKey_item(Integer.parseInt(rst.getString("key_item")));
                        taxDetail.setTax_value(rst.getString("tax_value"));
                        taxDetail.setTax_limit_val(Float.parseFloat(rst.getString("tax_limit_val")));
                        //////other details records ommited//////////////////////////
                        taxDetails.add(taxDetail);
                //a HashMap of all tax code as keys and list of details as values 4 each key
                for(int i = 0;i<itemTaxCodes.size(); i++){
                    itemTaxdetails.put(itemTaxCodes.get(i),taxDetails.get(i));
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return itemTaxdetails;
        //details of an item with all its taxes
        public List getAllItemDetails(String key_year,
                String key_office,String key_client,String key_company){
            List lineItems = new ArrayList();
            List itemNumbers = new ArrayList();
            Map taxDetails = new HashMap();
            LineItem item = null;
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            //A list of all item numbers in the declaration
            itemNumbers = getAllItemNumbers(key_year,
                    key_office,key_client,key_company);
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                for(Iterator itemIter= itemNumbers.iterator(); itemIter.hasNext();){
                    int itemNumber = ((Integer)itemIter.next()).intValue();
                    String select = "SELECT item_description,item_mass," +
                            "item_cost" +
                            " FROM " + Constants.WEB_TABLE +
                            " WHERE key_year = '"+key_year+"'" +
                            " AND key_office = '"+key_office+ "'"+
                            " AND key_client = '"+key_client+ "'"+
                            " AND key_company = '"+key_company+ "'"+
                            " AND key_item = " + itemNumber;
                    rst = stat.executeQuery(select);
                    while(rst.next()){
                        item = new LineItem();
                        item.setItem_description(rst.getString("item_description"));
                        item.setItem_mass(Float.parseFloat(rst.getString("item_mass")));
                        item.setKey_item(Integer.parseInt(rst.getString("item_cost")));
                        //////other details records ommited//////////////////////////
                        //A HashMap of all itemTaxeCodes as its keys and an ArrayList of itemTaxedetails as its values
                        taxDetails = getItemTaxDetails(item.getKey_year(),item.getKey_office(),
                                item.getKey_client(),item.getKey_company(),item.getKey_item());
                        //item tax details
                        item.setItmTaxes(taxDetails);
                        //list of items with tax details
                        lineItems.add(item);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return lineItems;
        public Set getDeclarations(String key_year,String key_cuo,
                String key_dec,String key_nber){
            List lineItems = new ArrayList();
            Set lineOrders = new HashSet();
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            LineOder lineOrder = null;
            String select = "SELECT * FROM " + Constants.WEB_TABLE +
                    " WHERE key_year = '" + key_year + "'" +
                    " AND key_cuo = '" + key_cuo + "'" +
                    " AND key_dec = '" + key_dec + "'" +
                    " AND key_nber = '" + key_nber + "'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                while(rst.next()){
                    lineOrder = new LineOder();
                    lineOrder.setKey_year(rst.getString("key_year"));
                    lineOrder.setKey_office(rst.getString("key_cuo"));
                    lineOrder.setKey_client(rst.getString("key_dec"));
                    lineOrder.setKey_company(rst.getString("key_nber"));
                    ////list of items with all their details
                    lineItems = getAllItemDetails(lineOrder.getKey_year(),lineOrder.getKey_office(),
                            lineOrder.getKey_client(),lineOrder.getKey_company());
                    //setting item details
                    lineOrder.setItems(lineItems);
                    //a list of order with all details
                    lineOrders.add(lineOrder);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return lineOrders;
    } and my testing servlet controller
    Controller.java
    package orderitems;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Controller extends HttpServlet {
        private Map taxDetails = new HashMap();
        //private List itemDetails = new ArrayList();
        //private Set orderDetails = new HashSet();
        private OrderDetails orderDetails = null;
        protected void processRequest(HttpServletRequest request,
                HttpServletResponse response)throws
                ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            String key_year = "2007";
            String key_office = "VZX00";
            String key_company = "DG20";
            String key_client =  "ZI001";
            int key_item = 1;
            String nextView = "/taxdetails_list.jsp";
            //String nextView = "/order_list.jsp";
            //String nextView = "/items_list.jsp";
            orderDetails = new OrderDetails();
            taxDetails = orderDetails.getItemTaxDetails(key_year,key_office,
                    key_company,key_client,key_item);
            //Store the collection objects into HTTP Request
            request.setAttribute("taxDetails", taxDetails);
            RequestDispatcher reqstDisp =
                    getServletContext().getRequestDispatcher(nextView);
            reqstDisp.forward(request,response);
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response)throws
                ServletException, IOException {
            processRequest(request, response);
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response)throws
                ServletException, IOException {
            processRequest(request, response);
    }I have not included code for beans to reduce on bulk.please help and with suggestions...
    Thanx in advance.
    Edited by: aiEx on Oct 3, 2007 8:13 AM

    aiEx wrote:
    sometimes a tap on the head is needed to really learn and understand :-)You're casting them to the String type while they are of the ItemTax type and you've confirmed it yourself. Likely you misunderstood the concepts behind "casting" and you was expecting some magic that they are automatically converted somehow from the ItemTax type to the String type while the ItemTax class isn't a subclass of the String class :)

  • Please Help::How to display a Map with LIsts as Keys and Values using JSTL

    Hi,
    I need some assistance on how to display a Map in JSP using struts or core JSTL. I have a HashMap which has a List of keys and each key maps to a value of an ArrayList.i.e I have an ArrayList of taxCodes and each taxCode maps to a value of taxDetails which is an ArrayList of details for for that particular taxCode. I have some trouble to display each taxCode then display taxDetails for each taxCode. Here is my code below:
    OrderDetails.java
    package orderitems;
    import java.sql.*;
    import java.util.*;
    public class OrderDetails {
        private LineOder lineOrder;
        private Map lineItems;
        //returns an item number, key_item, from its unique keys
        public int getItemNumber(int key_item, String key_year,
                String key_office,String key_client,String key_company){
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            int itmNum = 0;
             * key_item a unique number for an item.
             * key_year,key_office,key_client,key_company unique keys
             * for each order where this key_item is taken
             * from.
            String select = "SELECT key_item FROM "+
                    Constants.WEB_TABLE +" WHERE key_item = " + key_item +
                    " AND key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company +"'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                if(rst.next()){
                    itmNum = Integer.parseInt(rst.getString("key_item"));
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return itmNum;
        //get a list of item number(item codes)
        public List getAllItemNumbers(String key_year,
                String key_office,String key_client,String key_company){
            List itemNumbers = new ArrayList();
            LineItem itemNumber = null;
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            String select = "SELECT key_item FROM "+ Constants.WEB_TABLE +
                    " WHERE key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company + "'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                while(rst.next()){
                    itemNumber = new LineItem();
                    itemNumber.setKey_item(Integer.parseInt(rst.getString("key_item")));
                    itemNumbers.add(itemNumber);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return itemNumbers;
        //get a list of tax codes
        public List getAllTaxCodes(int key_item, String key_year,
                String key_office,String key_client,String key_company){
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            ItemTax taxCode;
            List taxCodes = new ArrayList();
            int itemNum = getItemNumber(key_item, key_year,
                    key_office,key_client,key_company);
            String select = "SELECT key_tax_code FROM "+
                    Constants.WEB_TABLE +" WHERE key_item = " + itemNum +
                    " AND key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company +"'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                while(rst.next()){
                    taxCode = new ItemTax();
                    taxCode.setKey_tax_code(rst.getString("key_tax_code"));
                    taxCodes.add(taxCode);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return taxCodes;
        /////This methode returns a Map which am trying to display in JSP
        //use tax code to get tax details
        public Map getItemTaxDetails(String key_year,String key_office,
                String key_client,String key_company,int key_item){
            ItemTax taxDetail = null;
            List taxDetails = new ArrayList();
            List itemTaxCodes = new ArrayList();
            Map itemTaxDetails = new HashMap();
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            //get a list of all tax codes of an item with a
            //given item number
            itemTaxCodes = getAllTaxCodes(key_item,key_year,
                    key_office,key_client,key_company);
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                for(Iterator taxCodeIter= itemTaxCodes.iterator(); taxCodeIter.hasNext();){
                    ItemTax itemTaxCode = (ItemTax)taxCodeIter.next();
                    String taxCode = itemTaxCode.getKey_tax_code();
                    String select = "SELECT tax_type,tax_value," +
                            "tax_limit_val FROM "+ Constants.WEB_TABLE +
                            " WHERE key_item = "+ key_item +
                            " AND key_year = '" + key_year + "'" +
                            " AND key_office = '" + key_office + "'" +
                            " AND key_client = '" + key_client + "'" +
                            " AND key_company = '" + key_company +"'" +
                            " AND key_tax_code = '" + taxCode + "'";
                    rst = stat.executeQuery(select);
                    while(rst.next()){
                        taxDetail = new ItemTax();
                        //records to be displayed only
                        taxDetail.setKey_item(Integer.parseInt(rst.getString("key_item")));
                        taxDetail.setTax_value(rst.getString("tax_value"));
                        taxDetail.setTax_limit_val(Float.parseFloat(rst.getString("tax_limit_val")));
                        //////other details records ommited//////////////////////////
                        taxDetails.add(taxDetail);////An ArrayList of taxDetails for each taxCode
                     * A HashMap which has all taxCodes of an item as its keys
                     * and an ArrayList of taxdetails as its values.
                     * I return this for display in a JSP.
                    itemTaxDetails.put(taxCode,taxDetails);
                System.out.println();
                System.out.println("*********CONSOLE OUTPUT*************");//display on console
                Set set = itemTaxDetails.keySet();
                Iterator iter = set.iterator();
                System.out.println("Key\t\tValue\r\n");
                while (iter.hasNext()) {
                    Object taxCode=iter.next();
                    Object details=itemTaxDetails.get(taxCode);
                    System.out.println(taxCode +"\t" + details);
                System.out.println("************************************");
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return itemTaxDetails;
        //details of an item with all its taxes
        public List getAllItemDetails(String key_year,
                String key_office,String key_client,String key_company){
            List lineItems = new ArrayList();
            List itemNumbers = new ArrayList();
            Map taxDetails = new HashMap();
            LineItem item = null;
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            //A list of all item numbers in the declaration
            itemNumbers = getAllItemNumbers(key_year,
                    key_office,key_client,key_company);
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                for(Iterator itemIter= itemNumbers.iterator(); itemIter.hasNext();){
                    LineItem itemNum = (LineItem)itemIter.next();
                    int itemNumber = itemNum.getKey_item();
                    String select = "SELECT item_description,item_mass," +
                            "item_cost" +
                            " FROM " + Constants.WEB_TABLE +
                            " WHERE key_year = '"+key_year+"'" +
                            " AND key_office = '"+key_office+ "'"+
                            " AND key_client = '"+key_client+ "'"+
                            " AND key_company = '"+key_company+ "'"+
                            " AND key_item = " + itemNumber;
                    rst = stat.executeQuery(select);
                    while(rst.next()){
                        item = new LineItem();
                        item.setItem_description(rst.getString("item_description"));
                        item.setItem_mass(Float.parseFloat(rst.getString("item_mass")));
                        item.setKey_item(Integer.parseInt(rst.getString("item_cost")));
                        //////other details records ommited//////////////////////////
                        /* A HashMap of all itemTaxeCodes as its keys and an
                         * ArrayList of itemTaxedetails as its values
                        taxDetails = getItemTaxDetails(item.getKey_year(),item.getKey_office(),
                                item.getKey_client(),item.getKey_company(),item.getKey_item());
                        //item tax details
                        item.setItmTaxes(taxDetails);
                        //list of items with tax details
                        lineItems.add(item);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return lineItems;
        public Set getOrders(String key_year,String key_office,
                String key_client,String key_company){
            List lineItems = new ArrayList();
            Set lineOrders = new HashSet();
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            LineOder lineOrder = null;
            String select = "SELECT * FROM " + Constants.WEB_TABLE +
                    " WHERE key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company + "'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                while(rst.next()){
                    lineOrder = new LineOder();
                    lineOrder.setKey_year(rst.getString("key_year"));
                    lineOrder.setKey_office(rst.getString("key_office"));
                    lineOrder.setKey_client(rst.getString("key_client"));
                    lineOrder.setKey_company(rst.getString("key_company"));
                    ////list of items with all their details
                    lineItems = getAllItemDetails(lineOrder.getKey_year(),lineOrder.getKey_office(),
                            lineOrder.getKey_client(),lineOrder.getKey_company());
                    //setting item details
                    lineOrder.setItems(lineItems);
                    //a list of order with all details
                    lineOrders.add(lineOrder);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return lineOrders;
    Controller.java
    package orderitems;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Controller extends HttpServlet {
        private Map taxDetails = new HashMap();
        private OrderDetails orderDetails = null;
        protected void processRequest(HttpServletRequest request,
                HttpServletResponse response)throws
                ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            String key_year = "2007";
            String key_office = "VZX00";
            String key_company = "DG20";
            String key_client =  "ZI001";
            int key_item = 1;
            String nextView = "/taxdetails_list.jsp";
            orderDetails = new OrderDetails();
            taxDetails = orderDetails.getItemTaxDetails(key_year,key_office,
                    key_company,key_client,key_item);
            //Store the collection objects into HTTP Request
            request.setAttribute("taxDetails", taxDetails);
            RequestDispatcher reqstDisp =
                    getServletContext().getRequestDispatcher(nextView);
            reqstDisp.forward(request,response);
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response)throws
                ServletException, IOException {
            processRequest(request, response);
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response)throws
                ServletException, IOException {
            processRequest(request, response);
    taxdetails_list.jsp
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <title>Simple Tax Detail Diaplay ::</title>
            <link rel="stylesheet" type="text/css" href="imgs/orders.css"/>
        </head>
        <body>
            <jsp:useBean id="taxDetails" class="java.util.HashMap" scope="request"/>
            <table>
                <c:forEach items="${taxDetails}" var="hMap">
                    <tr>
                        <td><c:out value="${hMap.key}" /></td>
                        <!--td><%--c:out value="${hMap.value}" /--%></td-->
                    </tr>
                </c:forEach>
            </table>
        </body>
    </html>am displaying taxCodes(in this case i have VAT and ICD) fine but cant figure out how to display a list of value for each taxCode.Here is the output am getting
    both in my JSP and on the console:
    *******************************CONSOLE OUTPUT****************************
    Key          Value
    ICD     [orderItems.ItemTax@13e6226, orderItems.ItemTax@9dca26]
    VAT [orderItems.ItemTax@13e6226, orderItems.ItemTax@9dca26]
    Edited by: aiEx on Oct 8, 2007 6:54 AM

    hi evnafets,
    yes i need a nested for loop.I have tried your advice but my bean properties are not found.Am getting this error:
    javax.servlet.ServletException: Unable to find a value for "key_item" in object of class "java.lang.String" using operator "."
    I have tried this as stated earlier in the post:I have tried to make the method getItemTaxDetails return a List and get the returned list value as taxDetails. I then tested to display this list on JSP and its displaying fine.
    public List getItemTaxDetails(String key_year,String key_office,
                String key_client,String key_company,int key_item){
            ItemTax taxDetail = null;
            List taxDetails = new ArrayList();
            List itemTaxCodes = new ArrayList();
            Map itemTaxDetails = new HashMap();
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            //get a list of all tax codes of an item with a
            //given item number
            itemTaxCodes = getAllTaxCodes(key_item,key_year,
                    key_office,key_client,key_company);
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                for(Iterator taxCodeIter= itemTaxCodes.iterator(); taxCodeIter.hasNext();){
                    ItemTax itemTaxCode = (ItemTax)taxCodeIter.next();
                    String taxCode = itemTaxCode.getKey_tax_code();
                    String select = "SELECT tax_type,tax_value," +
                            "tax_limit_val FROM "+ Constants.WEB_TABLE +
                            " WHERE key_item = "+ key_item +
                            " AND key_year = '" + key_year + "'" +
                            " AND key_office = '" + key_office + "'" +
                            " AND key_client = '" + key_client + "'" +
                            " AND key_company = '" + key_company +"'" +
                            " AND key_tax_code = '" + taxCode + "'";
                    rst = stat.executeQuery(select);
                    while(rst.next()){
                        taxDetail = new ItemTax();
                        //records to be displayed only
                        taxDetail.setKey_item(Integer.parseInt(rst.getString("key_item")));
                        taxDetail.setTax_value(rst.getString("tax_value"));
                        taxDetail.setTax_limit_val(Float.parseFloat(rst.getString("tax_limit_val")));
                        //////other details records ommited//////////////////////////
                        taxDetails.add(taxDetail);////An ArrayList of taxDetails for each taxCode
                     * A HashMap which has all taxCodes of an item as its keys
                     * and an ArrayList of taxdetails as its values.
                     * I return this for display in a JSP.
                    itemTaxDetails.put(taxCode,taxDetails);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            //return itemTaxDetails;
            return taxDetails;
        }And my JSP
    taxdetails_list.jsp
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <link rel="stylesheet" type="text/css" href="imgs/orders.css"/>
        </head>
        <body>
            <table>
                <c:forEach var="curRecord" items="${taxDetails}" varStatus="rowCounter">
                        <c:choose>
                            <c:when test="${rowCounter.count % 2 == 0}">
                                <c:set var="rowStyle" scope="page" value="odd" />
                            </c:when>
                            <c:otherwise>
                                <c:set var="rowStyle" scope="page" value="even" />
                            </c:otherwise>
                        </c:choose>
                        <tr class="${rowStyle}">
                            <td>${curRecord.key_item}</td>
                            <td>${curRecord.tax_value}</td>
                            <td>${curRecord.tax_limit_val}</td>
                        </tr>
                    </c:forEach>
            </table>
        </body>
    </html>I can't see where am going wrong even with your advice.Please help.
    Thnx.

  • Problem in comparision of two strings.please help..

    I am retriving a string password from database and another string from html(user entered one).when i am printing those two strings its printing same strings.But whenever i am comparing strings and printing its not showing equal it is printing as false.what might be the reason.please help me regarding this.Thank you in advance.My cosing is as follows:
    while(rs.next())
    pwd=rs.getString("password");
    System.out.println("pmfg is..."+pwd);
    System.out.println("first string..."+pwd);
    System.out.println("second string..."+loginpwd);
    if(pwd.equals(loginpwd))
    System.out.println("true.....");
    else
    System.out.println("false....");

    once you got two string objects ......forget for where they are comming (database or html0 ....focus on those objects ....do the following
    1) use trim() function on both strings which removes the whitespaces from front and end
    2) use equalsIgnoreCase
    if the problem still persists ....then forget your code and sue the SUN people

  • Java and MS SQL Server 2000 problem, please help

    please help me. I am using java and MS SQL Server 2000, and I'm trying to access and verify the login. I'm getting the following error message: [Microsoft][ODBC SQL Server Driver]Invalid Descriptor Index
    Can any please help in this regard.
    String userNumber = (String)userNumField.getValue();
    char[] userPasswordArray = userPasswordField.getPassword();
    String userPassword = new String(userPasswordArray);
         try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                java.sql.Connection connection = java.sql.DriverManager.getConnection("jdbc:odbc:Dikolobe_Data");
                java.sql.PreparedStatement statement = connection.prepareStatement(
                        "SELECT USER_NUMBER, USER_PASSWORD, USER_CLASS, USER_STATUS " +
                        "FROM SYS_USER " +
                        "WHERE (USER_NUMBER = ? AND USER_PASSWORD = ?);");
                statement.setString(1, userNumber);
                statement.setString(2, userPassword);
                java.sql.ResultSet result = statement.executeQuery();
                if(result.next()) {
                    String userStatus = result.getString(4);
                    if(userStatus.equals("logged on")) {
                        String loginErrorMessage = "User with number: " + userNumber + " is already logged on.";
                        javax.swing.JOptionPane loginErrorPane = getNarrowOptionPane(72);
                        loginErrorPane.setMessage(loginErrorMessage);
                        loginErrorPane.setMessageType(javax.swing.JOptionPane.ERROR_MESSAGE);
                        javax.swing.JDialog loginErrorDialog = loginErrorPane.createDialog(null, "Login Error");
                        loginErrorDialog.setVisible(true);
                    else {
                        String userClassification = result.getString(3);
                        if(userClassification.equals("Administrator")) {
                            AdminHomePage newAdminHomePage = new AdminHomePage();
                            newAdminHomePage.setVisible(true);
                        else if(userClassification.equals("Educator")) {
                            EduHomePage newEduHomePage = new EduHomePage();
                            newEduHomePage.setVisible(true);
                        statement = connection.prepareStatement(
                                "UPDATE SYS_USER SET USER_STATUS = ? " +
                                "WHERE USER_NUMBER = ?");
                        statement.setString(1, "logged on");
                        statement.setString(2, userNumber);
                        statement.executeUpdate();
                        dispose();
                }

    Doesn't the following link give you enough information?
    http://www.google.com/search?q=invalid+descriptor+index
    Anyway .. This error means that the given ResultSet column index which you're trying to retrieve the value from is out of the range.

  • Please help - Scrollable result set in sql server 2000

    Hi can some one please help me. I'm trying to create scrollable result set in sql server 2000, but i just can't get it to work. I've been trying to do this for the past 12 hours. I want to go home, but I can't till I get this going! please help!!! My crap code is as follows:
    package transact;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.JInternalFrame;
    import java.sql.*;
    import java.io.*;
    import java.util.*;
    public class DummyFrame extends Dummy
    protected String name, surname;
    protected Connection conn;
    protected CallableStatement cstatement;
    public DummyFrame()
    createFrame();
    private void createFrame()
    try
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
    conn = DriverManager.getConnection(
    "jdbc:microsoft:sqlserver://server:1433;" +
    "user=user;password=pwd;DatabaseName=Northwind");
    catch (Exception e)
    e.getMessage();
    populateFields();
    menuAction();
    show();
    private void menuAction()
    btncontacts.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    getRecords();
    populateFields();
    btncontacts.setText("NEXT");
    btnkeywords.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    // transaction.getRecords();
    nextRecord();
    populateFields();
    btncontacts.setText("NEXT");
    protected void nextRecord()
    try
    // CallableStatement cstatement = null;
    cstatement = conn.prepareCall(
    "{call Employee_Selection}", ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = cstatement.executeQuery();
    while (rs.next())
    surname = rs.getString("Lastname");
    cstatement.getMoreResults();
    catch (Exception e)
    e.getMessage();
    protected void getRecords()
    try
    CallableStatement cstatement = null;
    cstatement = conn.prepareCall(
    "{call Employee_Selection}", ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = cstatement.executeQuery();
    while (rs.next())
    surname = rs.getString("Lastname");
    name = rs.getString("Firstname");
    rs.first();
    // call stored procedure
    catch (Exception e)
    e.getMessage();
    // populate the fields;
    private void populateFields()
    txtfirstname.setText(name);
    txtsurname.setText(surname);
    }

    ummm ok i think the logic in your code is kinda screwy...
    here is what your should be doing.
    create the gui.
    get the resultset...
    have code that looks like this for nextRecord...
    protected void displayNextRecord(){
      // we do not call next here because we already called it last time
      surname = rs.getString("Lastname");
      name = rs.getString("Firstname");
      populateFields();
      if(!rs.next(){
        btncontacts.setEnabled(false);// i'm not sure what btncontacts is but we want to disable next becuase there are no more records...
    // in your intitalization code you need to do this...
    // you old stuff ending with...
    ResultSet rs = cstatement.executeQuery();
    // the new stuff...
    if(rs.first()){
      displayNextRecord();
    }else{
      btncontacts.setEnabled(false);//the result set is empty
    }ok the real problem you are having is that you are trying to display one record at a time but you are scrolling
    through the entire result set using while(rs.next()... what you
    want to do is create the result set once and scroll through
    it one item at a time with your gui.
    the example method i have given displays the data from the current
    row in your gui. then it advances the result set forward one row if possible. this method assumes that the result set will always
    be positioned on a valid row thus the need for calling
    rs.first() before we originally call displayNextRecord()
    well i hope you find this helpful.

  • Jtable Update problem .. Please help !!!!!!!!

    Hi ,
    I am trying to get my updated Jtable, stored in a table of database over a previous table ......after updating it via drag n drop ....
    But even after I change the cell position to make the changes ... it still takes up the old value of that cell and not the new one while writing the data in the database table...
    Here is the code .... Please see it and tell me if it is possible :
    package newpackage;
    import java.sql.*;
    import java.util.Vector;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Dimension;
    import java.text.*;
    import newpackage.ExcelExporter;
    import java.awt.Dimension;
    import javax.swing.border.*;
    import javax.swing.table.*;
    import java.awt.datatransfer.*;
    import java.awt.dnd.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.*;
    import java.awt.print.*;
    import java.awt.*;
    import java.io.*;
    import java.util.Random.*;
    import javax.swing.*;
    import java.text.*;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JComboBox;
    import javax.swing.JTable;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.TableColumn;
    public class tab7le extends javax.swing.JFrame {
        Vector columnNames = new Vector();
        Vector data = new Vector();
        Connection con;
    Statement stat;
    ResultSet rs;
    int li_cols = 0;
    Vector allRows;
    Vector row;
    Vector newRow;
    Vector colNames;
    String dbColNames[];
    String pkValues[];
    String tableName;
    ResultSetMetaData myM;
    String pKeyCol;
    Vector deletedKeys;
    Vector newRows;
    boolean ibRowNew = false;
    boolean ibRowInserted = false;
        private Map<String, Color> colormap = new HashMap<String, Color>();
        /** Creates new form tab7le */
        public tab7le() {
            populate();
            initComponents();
           public void updateDB(){
                     try{
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          catch (ClassNotFoundException e){
                System.out.println("Cannot Load Driver!");
          try{
             String url = "jdbc:odbc:FAMS";
             con = DriverManager.getConnection(url);
             stat = con.createStatement();
             rs = stat.executeQuery("Select * from SubAllot");
             deletedKeys = new Vector();
             newRows = new Vector();
             myM = rs.getMetaData();
             tableName = myM.getTableName(1);
             li_cols = myM.getColumnCount();
             dbColNames = new String[li_cols];
             for(int col = 0; col < li_cols; col ++){
                dbColNames[col] = myM.getColumnName(col + 1);
             allRows = new Vector();
             while(rs.next()){
                newRow = new Vector();
                for(int i = 1; i <= li_cols; i++){
                   newRow.addElement(rs.getObject(i));
                } // for
                allRows.addElement(newRow);
             } // while
          catch(SQLException e){
             System.out.println(e.getMessage());
    String updateLine[] = new String[dbColNames.length];
          try{
             DatabaseMetaData dbData = con.getMetaData();
             String catalog;
             // Get the name of all of the columns for this table
             String curCol;
             colNames = new Vector();
             ResultSet rset1 = dbData.getColumns(null,null,tableName,null);
             while (rset1.next()) {
                curCol = rset1.getString(4);
                colNames.addElement(curCol);
             rset1.close();
             pKeyCol = colNames.firstElement().toString();
             // Go through the rows and perform INSERTS/UPDATES/DELETES
             int totalrows;
             totalrows = allRows.size();
             String dbValues[];
             Vector currentRow = new Vector();
             pkValues = new String[allRows.size()];
             // Get column names and values
             for(int i=0;i < totalrows;i++){
                currentRow = (Vector) allRows.elementAt(i);
                int numElements = currentRow.size();
                dbValues = new String[numElements];
                for(int x = 0; x < numElements; x++){
                   String classType = currentRow.elementAt(x).getClass().toString();
                   int pos = classType.indexOf("String");
                   if(pos > 0){ // we have a String
                      dbValues[x] = "'" + currentRow.elementAt(x) + "'";
                      updateLine[x] = dbColNames[x] + " = " + "'" + currentRow.elementAt(x) + "',";
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                        pkValues[i] = currentRow.elementAt(x).toString() ;
                   pos = classType.indexOf("Integer");
                   if(pos > 0){ // we have an Integer
                      dbValues[x] = currentRow.elementAt(x).toString();
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                         pkValues[i] = currentRow.elementAt(x).toString();
                      else{
                         updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
                   pos = classType.indexOf("Boolean");
                   if(pos > 0){ // we have a Boolean
                      dbValues[x] = currentRow.elementAt(x).toString();
                      updateLine[x] = dbColNames[x] + " = " + currentRow.elementAt(x).toString() + ",";
                      if (dbColNames[x].toUpperCase().equals(pKeyCol.toUpperCase())){
                         pkValues[i] = currentRow.elementAt(x).toString() ;
                } // For Loop
                // If we are here, we have read one entire row of data. Do an UPDATE or an INSERT
                int numNewRows = newRows.size();
                int insertRow = 0;
                boolean newRowFound;
                for (int z = 0;z < numNewRows;z++){
                   insertRow = ((Integer) newRows.get(z)).intValue();
                   if(insertRow == i+1){
                      StringBuffer InsertSQL = new StringBuffer();
                      InsertSQL.append("INSERT INTO " + tableName + " (");
                      for(int zz=0;zz<=dbColNames.length-1;zz++){
                         if (dbColNames[zz] != null){
                            InsertSQL.append(dbColNames[zz] + ",");
                      // Strip out last comma
                      InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
                      InsertSQL.append(" VALUES(" + pkValues[i] + ",");
                      for(int c=1;c < dbValues.length;c++){
                         InsertSQL.append(dbValues[c] + ",");
                      InsertSQL.replace(InsertSQL.length()-1,InsertSQL.length(),")");
                      System.out.println(InsertSQL.toString());
                      stat.executeUpdate(InsertSQL.toString());
                      ibRowInserted=true;
                } // End of INSERT Logic
                // If row has not been INSERTED perform an UPDATE
                if(ibRowInserted == false){
                   StringBuffer updateSQL = new StringBuffer();
                   updateSQL.append("UPDATE " + tableName + " SET ");
                   for(int z=0;z<=updateLine.length-1;z++){
                      if (updateLine[z] != null){
                         updateSQL.append(updateLine[z]);
                   // Replace the last ',' in the SQL statement with a blank. Then add WHERE clause
                   updateSQL.replace(updateSQL.length()-1,updateSQL.length()," ");
                   updateSQL.append(" WHERE " + pKeyCol + " = " + pkValues[i] );
                   System.out.println(updateSQL.toString());
                   stat.executeUpdate(updateSQL.toString());
                   } //for
             catch(Exception ex){
                System.out.println("SQL Error! Cannot perform SQL UPDATE " + ex.getMessage());
             // Delete records from the DB
             try{
                int numDeletes = deletedKeys.size();
                String deleteSQL;
                for(int i = 0; i < numDeletes;i++){
                   deleteSQL = "DELETE FROM " + tableName + " WHERE " + pKeyCol + " = " +
                                                ((Integer) deletedKeys.get(i)).toString();
                System.out.println(deleteSQL);
                   stat.executeUpdate(deleteSQL);
                // Assume deletes where successful. Recreate Vector holding PK Keys
                deletedKeys = new Vector();
             catch(Exception ex){
                System.out.println(ex.getMessage());
        public void populate()
            try
                //  Connect to the Database
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection con = DriverManager.getConnection("Jdbc:Odbc:FAMS"," "," ");
                System.out.println("ok1");
                //  Read data from a table
                String sql;
                 sql = "Select * from SubAllot";
                 System.out.println("ok1");
                Statement stmt = con.createStatement();
                System.out.println("ok1");
                ResultSet rs = stmt.executeQuery( sql );
                System.out.println("ok1");
                ResultSetMetaData md = rs.getMetaData();
                System.out.println("ok1");
                int columns = md.getColumnCount();
                for(int i = 0;i<columns;i++){
                    columnNames.addElement(md.getColumnName(i+1));
                    System.out.println("ok2");
                while (rs.next())
                    Vector row = new Vector(columns);
                    for (int i = 1; i <columns+1; i++)
                        row.addElement( rs.getObject(i) );
                    data.addElement( row );
            catch(Exception e){
                e.printStackTrace();
                 public void dropmenu(JTable table,TableColumn subpref1) {
            //Set up the editor for the sport cells.
            JComboBox comboBox = new JComboBox();
          for (int i = 0;i<=20;i++)
           comboBox.addItem(i);
            subpref1.setCellEditor(new DefaultCellEditor(comboBox));
            //Set up tool tips for the sport cells.
            DefaultTableCellRenderer renderer =
                    new DefaultTableCellRenderer();
            renderer.setToolTipText("Click for combo box");
            subpref1.setCellRenderer(renderer);
                       abstract class StringTransferHandler extends TransferHandler {
            public int dropAction;
            protected abstract String exportString(final JComponent c);
            protected abstract void importString(final JComponent c, final String str);
            @Override
            protected Transferable createTransferable(final JComponent c) {
                return new StringSelection(exportString(c));
            @Override
            public int getSourceActions(final JComponent c) {
                return MOVE;
            @Override
            public boolean importData(final JComponent c, final Transferable t) {
                if (canImport(c, t.getTransferDataFlavors())) {
                    try {
                        String str = (String) t.getTransferData(DataFlavor.stringFlavor);
                        importString(c, str);
                        return true;
                    } catch (UnsupportedFlavorException ufe) {
                    } catch (IOException ioe) {
                return false;
            @Override
            public boolean canImport(final JComponent c, final DataFlavor[] flavors) {
                for (int ndx = 0; ndx < flavors.length; ndx++) {
                    if (DataFlavor.stringFlavor.equals(flavors[ndx])) {
                        return true;
                return false;
        class TableTransferHandler extends StringTransferHandler {
            private int dragRow;
            private int[] dragColumns;
            private BufferedImage[] image;
            private int row;
            private int[] columns;
            public JTable target;
            private Map<String, Color> colormap;
            private TableTransferHandler(final Map<String, Color> colormap) {
                this.colormap = colormap;
            @Override
            protected Transferable createTransferable(final JComponent c) {
                JTable table = (JTable) c;
                dragRow = table.getSelectedRow();
                dragColumns = table.getSelectedColumns();
                createDragImage(table);
                return new StringSelection(exportString(c));
            protected String exportString(final JComponent c) {
                JTable table = (JTable) c;
                row = table.getSelectedRow();
                columns = table.getSelectedColumns();
                StringBuffer buff = new StringBuffer();
                colormap.clear();
                for (int j = 0; j < columns.length; j++) {
                    Object val = table.getValueAt(row, columns[j]);
                    buff.append(val == null ? "" : val.toString());
                    if (j != columns.length - 1) {
                        buff.append(",");
                    colormap.put(row+","+columns[j], Color.LIGHT_GRAY);
                table.repaint();
                return buff.toString();
            protected void importString(final JComponent c, final String str) {
                target = (JTable) c;
                DefaultTableModel model = (DefaultTableModel) target.getModel();
                String[] values = str.split("\n");
                int colCount = target.getSelectedColumn();
                int max = target.getColumnCount();
                for (int ndx = 0; ndx < values.length; ndx++) {
                    String[] data = values[ndx].split(",");
                    for (int i = 0; i < data.length; i++) {
                        String string = data;
    if(colCount < max){
    Object val = model.getValueAt(target.getSelectedRow(), colCount);
    model.setValueAt(string, target.getSelectedRow(), colCount);
    model.setValueAt(val, dragRow, dragColumns[i]);
    colCount++;
    public BufferedImage[] getDragImage() {
    return image;
    private void createDragImage(final JTable table) {
    if (dragColumns != null) {
    try {
    image = new BufferedImage[dragColumns.length];
    for (int i = 0; i < dragColumns.length; i++) {
    Rectangle cellBounds = table.getCellRect(dragRow, i, true);
    TableCellRenderer r = table.getCellRenderer(dragRow, i);
    DefaultTableModel m = (DefaultTableModel) table.getModel();
    JComponent lbl = (JComponent) r.getTableCellRendererComponent(table,
    table.getValueAt(dragRow, dragColumns[i]), false, false, dragRow, i);
    lbl.setBounds(cellBounds);
    BufferedImage img = new BufferedImage(lbl.getWidth(), lbl.getHeight(),
    BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D graphics = img.createGraphics();
    graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.6f));
    lbl.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
    lbl.paint(graphics);
    graphics.dispose();
    image[i] = img;
    } catch (RuntimeException re) {
    class TableDropTarget extends DropTarget {
    private Insets autoscrollInsets = new Insets(20, 20, 20, 20);
    private Rectangle rect2D = new Rectangle();
    private TableTransferHandler handler;
    public TableDropTarget(final TableTransferHandler h) {
    super();
    this.handler = h;
    @Override
    public void dragOver(final DropTargetDragEvent dtde) {
    handler.dropAction = dtde.getDropAction();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    Point location = dtde.getLocation();
    int row = table.rowAtPoint(location);
    int column = table.columnAtPoint(location);
    table.changeSelection(row, column, false, false);
    paintImage(table, location);
    autoscroll(table, location);
    super.dragOver(dtde);
    public void dragExit(final DropTargetDragEvent dtde) {
    clearImage((JTable) dtde.getDropTargetContext().getComponent());
    super.dragExit(dtde);
    @Override
    public void drop(final DropTargetDropEvent dtde) {
    Transferable data = dtde.getTransferable();
    JTable table = (JTable) dtde.getDropTargetContext().getComponent();
    clearImage(table);
    handler.importData(table, data);
    super.drop(dtde);
    private final void paintImage(final JTable table, final Point location) {
    Point pt = new Point(location);
    BufferedImage[] image = handler.getDragImage();
    if (image != null) {
    table.paintImmediately(rect2D.getBounds());
    rect2D.setLocation(pt.x - 15, pt.y - 15);
    int wRect2D = 0;
    int hRect2D = 0;
    for (int i = 0; i < image.length; i++) {
    table.getGraphics().drawImage(image[i], pt.x - 15, pt.y - 15, table);
    pt.x += image[i].getWidth();
    if (hRect2D < image[i].getHeight()) {
    hRect2D = image[i].getHeight();
    wRect2D += image[i].getWidth();
    rect2D.setSize(wRect2D, hRect2D);
    private final void clearImage(final JTable table) {
    table.paintImmediately(rect2D.getBounds());
    private Insets getAutoscrollInsets() {
    return autoscrollInsets;
    private void autoscroll(final JTable table, final Point cursorLocation) {
    Insets insets = getAutoscrollInsets();
    Rectangle outer = table.getVisibleRect();
    Rectangle inner = new Rectangle(outer.x + insets.left,
    outer.y + insets.top,
    outer.width - (insets.left + insets.right),
    outer.height - (insets.top + insets.bottom));
    if (!inner.contains(cursorLocation)) {
    Rectangle scrollRect = new Rectangle(cursorLocation.x - insets.left,
    cursorLocation.y - insets.top,
    insets.left + insets.right,
    insets.top + insets.bottom);
    table.scrollRectToVisible(scrollRect);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    table = new javax.swing.JTable();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    table.setModel(new javax.swing.table.DefaultTableModel(
    data, columnNames
    jScrollPane1.setViewportView(table);
    //populate();
    table.getTableHeader().setReorderingAllowed(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setCellSelectionEnabled(true);
    table.setDragEnabled(true);
    TableTransferHandler th = new TableTransferHandler(colormap);
    table.setTransferHandler(th);
    table.setDropTarget(new TableDropTarget(th));
    dropmenu(table, table.getColumnModel().getColumn(11));
    jButton1.setText("Update");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    jButton2.setText("Ex");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(92, 92, 92)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 605, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(layout.createSequentialGroup()
    .addGap(347, 347, 347)
    .addComponent(jButton1)
    .addGap(115, 115, 115)
    .addComponent(jButton2)))
    .addContainerGap(73, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(47, 47, 47)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(58, 58, 58)
    .addComponent(jButton1)
    .addContainerGap(83, Short.MAX_VALUE))
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jButton2)
    .addGap(65, 65, 65))))
    pack();
    }// </editor-fold>
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    updateDB(); // TODO add your handling code here:
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    try {
    String pathToDesktop = System.getProperty("user.home")+File.separator+"Desktop";
    pathToDesktop = pathToDesktop + "//Final Allotment.xls";
    ExcelExporter exp = new ExcelExporter();
    exp.exportTable(table, new File(pathToDesktop));
    JOptionPane.showMessageDialog(this,"File exported and saved on desktop!");
    catch (IOException ex) {
    System.out.println(ex.getMessage());
    ex.printStackTrace();
    } // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new tab7le().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable table;
    // End of variables declaration
    Please help !!!!!!!!
    Thanks in advance.....                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

    Here is the code Do you expect people to read through 400 lines of code to understand what you are doing?
    Why post code with access to a database? We can't access the database.
    Search the forum for my "Database Information" (without the space) example class which shows you how to refresh a table with new data.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • Query Prepared Statement Does NOT Return ANY Values !URGENT! PLEASE HELP...

    Hi,
    Please help me in the following.I'm desperate...
    I'm using PreparedStatement to do multiple queries in the same Table of a Database(ACCESS).
    The rows of the Table look i.e like this :
    (TABLE NAME == PERSONS)
    PERSON_INDEX__TIME_PERIOD_________SPORT
    1_______________1________________Basketball
    1_______________2________________Football
    1_______________3________________Tennis
    2_______________1________________Something
    I populate my PreparedStatement using something like :
    java.sql.PreparedStatement st = con.createPreparedStatement("SELECT SPORT FROM PERSONS WHERE PERSON_INDEX=? AND TIME_PERIOD=?");
    Now, when I do something like :
    try
    st.setInt(1,1);
    st.setInt(2,1);
    st.addBatch();
    }catch(SQLException e){}
    st.executeQuery();
    ResultSet results = st.getResultSet();
    while ( results.next() )
    System.out.println("->"+results.getString("SPORT"));
    I trully get as output :
    ->BasketBall
    But when I populate it some more :
    try
    st.setInt(1,1);
    st.setInt(2,1);
    st.addBatch();
    //***Query some more***
    st.setInt(1,1);
    st.setInt(2,2);
    st.addBatch();
    }catch(SQLException e){}
    ... and I execute I DON'T GET :
    ->BasketBall
    ->Football
    but NOTHING!!! - the ResultSet HAS NO ROWS
    This thing is driving me mad.
    Can you please help me out?
    Please post the code if neccessary...

    There is something wrong in your understanding of batching the statements. Basically you will add either update or insert or delete statements to your batch.
    If you add a select statement, it will throw 'java.sql.BatchUpdateException: invalid batch command'. And moreover 'st.executeBatch()' is the method you need to invoke.
    If you don't execute the batch using 'executeBatch()' method then, it must throw the exception,
    'java.sql.SQLException: error occurred during batching: batch must be either executed or cleared'.
    You need to rework on your code, I believe.
    Sudha

  • JDBC for Postgresql(on Linux): java.lang.NullPointerExceptio--Please HELP!

    I'm trying to build a JSP web application with Apache Tomcat 4.0 on Linux, using PostgreSQL database.
    The test page for building a connection to the database is very simple.
    However, unfortunately, I always get the following error message from the web server.
    The code is also show below.
    I have another Tomcat server working on Window2000 with Oracle. So I change the JDBC driver to Oracle on that machine, and it works fine.
    I guessed I might have some problem with the Tomcat setting, but I'm not sure what I need to change.
    The directory of my web application is built under the webapps.
    And I've added JAVA_HOME, JAVA_HOME/lib/tool.jar, and JDBC for PostgreSQL to my CLASSPATH.
    Is there any other configuration that I missed?
    Please help if you see the problem.
    Thanks a lot in advance.
    Error message:
    type: Exception report
    message: Internal Server Error
    description: The server encountered an internal error (Internal Server Error) that prevented it from fulfilling this request.
    exception
    java.lang.NullPointerException
         at org.apache.jsp.index$jsp._jspService(index$jsp.java:231)
         at org.apache.jasper.runtime.HttpJspBase.service(Unknown Source)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(Unknown Source)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(Unknown Source)
         at org.apache.jasper.servlet.JspServlet.service(Unknown Source)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(Unknown Source)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(Unknown Source)
         at org.apache.catalina.core.StandardWrapperValve.invoke(Unknown Source)
         at org.apache.catalina.core.StandardPipeline.invokeNext(Unknown Source)
         at org.apache.catalina.core.StandardPipeline.invoke(Unknown Source)
         at org.apache.catalina.core.ContainerBase.invoke(Unknown Source)
         at org.apache.catalina.core.StandardContextValve.invoke(Unknown Source)
         at org.apache.catalina.core.StandardPipeline.invokeNext(Unknown Source)
         at org.apache.catalina.core.StandardPipeline.invoke(Unknown Source)
         at org.apache.catalina.core.ContainerBase.invoke(Unknown Source)
         at org.apache.catalina.core.StandardContext.invoke(Unknown Source)
         at org.apache.catalina.core.StandardHostValve.invoke(Unknown Source)
         at org.apache.catalina.core.StandardPipeline.invokeNext(Unknown Source)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(Unknown Source)
         at org.apache.catalina.core.StandardPipeline.invokeNext(Unknown Source)
         at org.apache.catalina.valves.ErrorReportValve.invoke(Unknown Source)
         at org.apache.catalina.core.StandardPipeline.invokeNext(Unknown Source)
         at org.apache.catalina.valves.AccessLogValve.invoke(Unknown Source)
         at org.apache.catalina.core.StandardPipeline.invokeNext(Unknown Source)
         at org.apache.catalina.core.StandardPipeline.invoke(Unknown Source)
         at org.apache.catalina.core.ContainerBase.invoke(Unknown Source)
         at org.apache.catalina.core.StandardEngineValve.invoke(Unknown Source)
         at org.apache.catalina.core.StandardPipeline.invokeNext(Unknown Source)
         at org.apache.catalina.core.StandardPipeline.invoke(Unknown Source)
         at org.apache.catalina.core.ContainerBase.invoke(Unknown Source)
         at org.apache.catalina.connector.http.HttpProcessor.process(Unknown Source)
         at org.apache.catalina.connector.http.HttpProcessor.run(Unknown Source)
         at java.lang.Thread.run(Thread.java:484)
    Here's my code:
    <%@ page language="java" import="java.io.*, java.sql.*, java.util.*, java.lang.*" %>
    <HTML>
    <HEAD>
    <TITLE>TEST</TITLE>
    </HEAD>
    <BODY>
    <b> City </b><br>
    <%
         Class.forName("org.postgresql.Driver");
         String sqlurl = "jdbc:postgresql://localhost:5432/customer";
         String username = "guest";
         String passwd = username;
         Connection conn = DriverManager.getConnection(sqlurl, username, passwd);
         Statement st = conn.createStatement();
         String queryStr = "select CITY from WEATHER";
         ResultSet rs = st.executeQuery(queryStr);
         if (rs != null){
              while(rs.next()){
                   String strCity = rs.getString(1);
    %>
    -- <%=strCity %> --<br>
    <%
         st.close();
         conn.close();
    %>
    </BODY>
    </HTML>

    Error is not there in the code what you are showing. Can you edit index$jsp.java and see what is there in line 231?
    You may find it in tomcat_home\work\your_application directory.
    Sudha

  • Getting problem in tag libraries,please help!!!

    hello.
    i am writing simple tag for accessing database.
    i am getting follwing error
    =======================================================================
    weblogic.servlet.jsp.JspException: (line 26): Could not parse deployment descrip
    tor: java.io.IOException: cannot resolve '/WEB-INF/DemoTags.tld' into a valid ta
    g library
    at weblogic.servlet.jsp.JspLexer.jspException(JspLexer.java:863)
    at weblogic.servlet.jsp.JspLexer.mTAGLIB_DIRECTIVE_BODY(JspLexer.java:47
    14)
    at weblogic.servlet.jsp.JspLexer.mTAGLIB_DIRECTIVE(JspLexer.java:4538)
    at weblogic.servlet.jsp.JspLexer.mDIRECTIVE(JspLexer.java:4385)
    at weblogic.servlet.jsp.JspLexer.mSTANDARD_THING(JspLexer.java:2223)
    at weblogic.servlet.jsp.JspLexer.mTOKEN(JspLexer.java:2006)
    at weblogic.servlet.jsp.JspLexer.nextToken(JspLexer.java:1888)
    at weblogic.servlet.jsp.JspLexer.parse(JspLexer.java:1107)
    at weblogic.servlet.jsp.JspParser.doit(JspParser.java:89)
    at weblogic.servlet.jsp.JspParser.parse(JspParser.java:193)
    at weblogic.servlet.jsp.Jsp2Java.outputs(Jsp2Java.java:119)
    at weblogic.utils.compiler.CodeGenerator.generate(CodeGenerator.java:255
    at weblogic.servlet.jsp.JspStub.compilePage(JspStub.java:341)
    at weblogic.servlet.jsp.JspStub.prepareServlet(JspStub.java:201)
    at weblogic.servlet.jsp.JspStub.prepareServlet(JspStub.java:154)
    at weblogic.servlet.internal.ServletStubImpl.getServlet(ServletStubImpl.
    java:370)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
    pl.java:240)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
    pl.java:321)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
    pl.java:198)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppSe
    rvletContext.java:2637)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestIm
    pl.java:2359)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:139)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
    ========================================================================
    i am using weblogic 6.1
    i have put my tld file in /WEB-INF/DemoTags.tld
    i don;t know why i getting this error.
    my tld file is as follow.
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
    "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
    <taglib>
    <tlibversion>1.0</tlibversion>
    <jspversion>1.2</jspversion>
    <shortname>DemoTags</shortname>
    <uri>http://www.stardeveloper.com</uri>
    <info>Demo Tags Library</info>
    <tag>
    <name>displaydata</name>
    <tagclass>Tags.DataAccessTag</tagclass>
    <teiclass>Tags.DataAccessTagTEI</teiclass>
    <bodycontent>JSP</bodycontent>
    <info>Data Access Tag.</info>
    </tag>
    </taglib>
    and my class file is in /WEB-INF/classes/Tags/DataAccessTags.java
    and /WEB-INF/classes/Tags/DataAccessTagsTEI.java
    package Tags;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import javax.servlet.jsp.*;
    import javax.servlet.jsp.tagext.*;
    import javax.servlet.jsp.tagext.BodyTag;
    import javax.servlet.jsp.tagext.Tag;
    public class DataAccessTag implements BodyTag
         private PageContext pc=null;
         private BodyContent body=null;
         private StringBuffer sb=new StringBuffer();
         private Connection conn=null;
         private Statement stmt=null;
         private ResultSet rs=null;
         public void setPageContext(PageContext p)
              pc=p;
         public void setParent(Tag t)
         public Tag getParent()
              return null;
         public int doStartTag() throws JspException
              String path="jdbc:odbc:Names";
              String sql="select ID,first_name,last_name from Names";
              try
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   conn=DriverManager.getConnection(path);
                   stmt=conn.createStatement();
                   rs=stmt.executeQuery(sql);
                   setVariables();
              }catch(SQLException e)
                   throw new JspTagException("An SQLException occured");
              }catch(ClassNotFoundException e)
                   throw new JspTagException("Jdbc driver not found");
              return EVAL_BODY_TAG;
         public void setBodyContent(BodyContent b)
              body=b;
         public void doInitBody() throws JspException{}
         private boolean setVariables() throws JspTagException
              try
                   if(rs.next())
                        pc.setAttribute("id",rs.getObject(1).toString());
                        pc.setAttribute("first_name",rs.getObject(2).toString());
                        pc.setAttribute("last_name",rs.getObject(3).toString());
                        return true;
                   }else
                        return false;
              }catch(SQLException e){
                   throw new JspTagException("SQLException occured");
         public int doAfterBody() throws JspException
              try{
                   sb.append(body.getString());
                   body.clear();
              }catch(IOException e){
                   throw new JspTagException("Fatal IOException");
              if(setVariables())
                   return EVAL_BODY_TAG;
              try{
                   body.getEnclosingWriter().write(sb.toString());
              }catch(IOException e){
                   throw new JspTagException("fatal IOException");
              return SKIP_BODY;
         public int doEndTag() throws JspException
              try{
                   if(rs!=null)
                        rs.close();
                        rs=null;
                   if(stmt!=null)
                        stmt.close();
                        stmt=null;
                   if(conn!=null)
                        conn.close();
                        conn=null;
              }catch(SQLException e){
              return EVAL_PAGE;
         public void release()
              pc=null;
              body=null;
              sb=null;
    and DataAccessTagTEI.java
    package Tags;
    import javax.servlet.jsp.tagext.*;
    public class DataAccessTagTEI extends TagExtraInfo
         public VariableInfo[] getVariableInfo(TagData data)
              return new VariableInfo[]{
                   new VariableInfo("id","java.lang.String",true,VariableInfo.NESTED),
                   new VariableInfo("first_name","java.lang.String",true,VariableInfo.NESTED),
                   new VariableInfo("last_name","java.lang.String",true,VariableInfo.NESTED)
    please help me...

    package your class(es) as a jar file and put in the lib directory of your web application.

  • How to acess Database in I18N? Please help.

    How to acess Database in I18N? Please help.

    I have tried to overide the getContents() method of ListResourceBundle class but it returning an error at run time saying null Pointer exception.
    Here are the 2 codes resp.
    import java.util.*;
    public class Test1
         static String string ;
         public static void main(String args[])
    Locale locale = Locale.ENGLISH;
    ResourceBundle myResources =
    ResourceBundle.getBundle("MyResources", locale);
    string = myResources.getString("HelpKey");
    System.out.println(string);
    import java.util.*;
    import java.sql.*;
    public class MyResources extends ListResourceBundle
         static String[][] s3= null;
    String s6= null;
         String s7= null;
    public Object[][] getContents()
    Object[][] obj= (Object[][])dataBase();
              for(int i= 0; i< obj.length;++i){
                   for(int j = 0;j<obj.length;++j){
                        System.out.println("GGGGGGGG obj["+i+"]["+j+"]"+obj[i][j]);
              //s6=(String)obj[0][0];
         //     s6= obj[0][0].toString();
              //s7=obj[1][0].toString();
    Object[][] contents = { {s6},{s7}};
         return contents;
         private static String[][] dataBase()
         {           try
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   Connection con=DriverManager.getConnection("jdbc:odbc:DSN");
                   PreparedStatement stat= con.prepareStatement("Select Value,Key from Table1 where Key= ?");
                   String s1= "HelpKey";
                   stat.setString(1,s1);
                   ResultSet rs= stat.executeQuery();
                   while(rs.next())
                        String s2= (String)rs.getString("Key");
                        String s4= (String)rs.getString("Value");
                        String[][] s3 ={{s2},{s4}};
              catch(Exception e)
              e.printStackTrace();
         return s3;

  • Please help me with my code (has conversion from string to int)

    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    public class Test3 extends MIDlet implements CommandListener
    {   Form mForm;
        Command mCommandQuit;
        Command mCommandItem;
        TextField input,prime1,prime2,prime3,output;
        Display mDisplay;
        int i,j=0,k1,k2,p,q,b;
        //int [] current=new int [1000];
        String mstring,a="";
        String [] temp=new String [1000];
        public void startApp()
        {System.out.println("startApp");
         mForm=new Form("RSA Encryption");
         mCommandQuit=new Command("QUIT",Command.EXIT,0);
         mCommandItem=new Command("ENCRYPT",Command.ITEM,0);
         mForm.append("Enter text:\n");
         input=new TextField(null,"",100, TextField.ANY);
         mForm.append(input);
         mForm.append("Enter first prime number(p):\n");
         prime1=new TextField(null,"",100, TextField.ANY);
         mForm.append(prime1);
         mForm.append("Enter second prime number(q):\n");
         prime2=new TextField(null,"",100, TextField.ANY);
         mForm.append(prime2);
         mForm.append("Enter d:\n");
         prime3=new TextField(null,"",100, TextField.ANY);
         mForm.append(prime3);
         mForm.addCommand(mCommandQuit);
         mForm.addCommand(mCommandItem);
         mDisplay=Display.getDisplay(this);
         mDisplay.setCurrent(mForm);
         mForm.setCommandListener(this);
        public void pauseApp()
        {System.out.println("pauseApp");
        public void destroyApp(boolean unconditional)
        {System.out.println("destroyApp");
        public void commandAction(Command c, Displayable d)
        {System.out.println("commandAction");
         if(c==mCommandQuit)
            notifyDestroyed();
         else if(c==mCommandItem)
         {p = Integer.parseInt(prime1.getString());
             q = Integer.parseInt(prime2.getString());
             b = Integer.parseInt(prime3.getString());
             //breaking up of big string into ints
             mstring=input.getString();
             temp[0]="";
             for(i=1;i<mstring.length();i++)
                {if (mstring.charAt(i) == ' ')
                    {j++;
                     temp[j]="";
                 else
                    {temp[j]=temp[j]+mstring.charAt(i);
             mForm.append("\n\nThe array is:\n");
             for(i=0;i<temp.length && temp!=null;i++)
    {k1=Integer.parseInt(temp[i]); ***********************
    k2=k1;
    for(j=1;j<b;j++)
    {k1=k1*k2;
    k1=k1 %(p*q);
    k2=k1 %(p*q);
    a=a+new Character((char)k2).toString();
    output=new TextField(null,a,100, TextField.ANY);
    mForm.append(output);
    }hi
    this code basically takes an input of string like " 179 84 48 48 155 " (with spaces)
    then it creates smaller strings in an array like "179","84","48","48","155" without the spaces
    then it creates int values 179,84,48,48,155 and finally after some math functions it prints the corresponding letters.
    the problem is that it is not printing the letter because of some exceptions-->java.lang.NumberFormatException .it comes in the line where i have put stars
    could anybody please help me print the letters                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    thanks for all ur help guys, but me and my team member solved it on our own. here is the new code:
    import javax.microedition.midlet.*;
    import javax.microedition.lcdui.*;
    public class Test3 extends MIDlet implements CommandListener
    {   Form mForm;
        Command mCommandQuit;
        Command mCommandItem;
        TextField input,prime1,prime2,prime3,output;
        Display mDisplay;
        int i,j=0,l,k1,k2,p,q,n,b;
        String mstring,a = "";
        String [] temp=new String [1000];
        public void startApp()
        {System.out.println("startApp");
         mForm=new Form("RSA Encryption");
         mCommandQuit=new Command("QUIT",Command.EXIT,0);
         mCommandItem=new Command("DECRYPT",Command.ITEM,0);
         mForm.append("Enter text:\n");
         input=new TextField(null,"",100, TextField.ANY);
         mForm.append(input);
         mForm.append("Enter first prime number(p):\n");
         prime1=new TextField(null,"",100, TextField.NUMERIC);
         mForm.append(prime1);
         mForm.append("Enter second prime number(q):\n");
         prime2=new TextField(null,"",100, TextField.NUMERIC);
         mForm.append(prime2);
         mForm.append("Enter d:\n");
         prime3=new TextField(null,"",100, TextField.NUMERIC);
         mForm.append(prime3);
         mForm.addCommand(mCommandQuit);
         mForm.addCommand(mCommandItem);
         mDisplay=Display.getDisplay(this);
         mDisplay.setCurrent(mForm);
         mForm.setCommandListener(this);
        public void pauseApp()
        {System.out.println("pauseApp");
        public void destroyApp(boolean unconditional)
        {System.out.println("destroyApp");
        public void commandAction(Command c, Displayable d)
        {System.out.println("commandAction");
         if(c==mCommandQuit)
            notifyDestroyed();
         else if(c==mCommandItem)
         {p = Integer.parseInt(prime1.getString());
             q = Integer.parseInt(prime2.getString());
             b = Integer.parseInt(prime3.getString());
             n=p*q;
             //breaking up of big string into ints
             mstring=input.getString();
             temp[0]="";
             for(i=1;i<mstring.length();i++)
                {if (mstring.charAt(i) == ' ')
                    {j++;
                     temp[j]="";
                 else
                    {temp[j]=temp[j]+mstring.charAt(i);
             l=j;
             mForm.append("\n\nThe result is:\n");
             for(i=0;i<l;i++)
                {k1=Integer.valueOf(temp).intValue();
    k2=k1;
    for(j=1;j<b;j++)
    {k2=k2*k1;
    k2=k2 %n;
    k1=k2 %n;
    a=a+new Character((char)k1).toString();
    output=new TextField(null,a,100, TextField.ANY);
    mForm.append(output);

  • Please Help Me, Delete Method(any suggestions!!)

    Can anyone spare the time to look at the below three classes and suggest a method that goes into the customerList class and deletes a record from the Oracle DB they are sitting on top of.
    For example when the deleteCust button is pressed on the form (customerForm) I would like it to delete the current customer (currentCustomer) that is displayed on the form at the time of the button click.
    Can anyone please HELP me, it would be very much appreciated :-)
    customer class
    import java.util.*;
    import java.sql.*;
    public class Customer{
    private int customer_id;
    private String customer_name;
    private String address1;
    private String address2;
    private String town;
    private String county;
    private String post_code;
    private String country;
    private String fax;
    private String telephone;
    private String contact_name;
    private String email;
    private boolean newCustomer;
    //private JobList jobList;
    public Customer(int c){
    customer_id = c;
    newCustomer = true;
    public Customer(int inCustomer_id,String inCustomer_name,String inAddress1, String inAddress2, String inTown, String inCounty,String inPost_code,String inCountry,String inFax,String inTelephone,String inContact_name,String inEmail){
    customer_id=inCustomer_id;
    customer_name=inCustomer_name;
    address1=inAddress1;
    address2=inAddress2;
    town=inTown;
    county=inCounty;
    post_code=inPost_code;
    country=inCountry;
    fax=inFax;
    telephone=inTelephone;
    contact_name=inContact_name;
    email=inEmail;
    newCustomer = false;
    public String getAddress1(){
    if (address1 == null)
    return ("");
    else
    return address1;
    public String getAddress2(){
    if (address2 == null)
    return ("");
    else
    return address2;
    public String getCounty(){
    if (county == null)
    return ("");
    else
    return county;
    public String getFax(){
    if (fax == null)
    return ("");
    else
    return fax;
    public int getCustomer_id(){
    if (customer_id == 0)
    return (0);
    else
    return customer_id;
    public String getCustomer_name(){
    if (customer_name == null)
    return ("");
    else
    return customer_name;
    public String getTelephone(){
    if (telephone == null)
    return ("");
    else
    return telephone;
    public String getPost_code(){
    if (post_code == null)
    return ("");
    else
    return post_code;
    public String getTown(){
    if (town == null)
    return ("");
    else
    return town;
    public String getCountry(){
    if (country == null)
    return ("");
    else
    return country;
    public String getContact_name(){
    if (contact_name == null)
    return ("");
    else
    return contact_name;
    public String getEmail(){
    if (email == null)
    return ("");
    else
    return email;
    /*public JobList getJobList() throws SQLException {
    // if the joblist object exists return it otherwise create it
    if (jobList != null){
    return jobList;
    else{
    return new JobList(this);
    public boolean isNewCustomer(){
    return newCustomer;
    public void setAddress1(String inAddress1){
    address1=inAddress1;
    public void setAddress2(String inAddress2){
    address2=inAddress2;
    public void setCounty(String inCounty){
    county=inCounty;
    public void setFax(String inFax){
    fax=inFax;
    public void setCustomer_id(int inCustomer_id){
    customer_id = inCustomer_id;
    public void setCustomer_name(String inCustomer_name){
    customer_name=inCustomer_name;
    public void setTelephone(String inTelephone){
    telephone=inTelephone;
    public void setPost_code(String inPost_code){
    post_code=inPost_code;
    public void setTown(String inTown){
    town=inTown;
    public void setCountry(String inCountry){
    country=inCountry;
    public void setContact_name(String inContact_name){
    contact_name=inContact_name;
    public void setEmail(String inEmail){
    email=inEmail;
    customerList class
    import java.sql.*;
    import java.util.*;
    public class CustomerList{
    private ResultSet rs ;
    private Connection con;
    private Statement stmt;
    public CustomerList () {
    ConnectionManager man = ConnectionManager.getInstance();
    con = man.getConnection();
    public Customer getFirstCustomer()throws SQLException {
    Customer firstCustomer;
    stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery("select customer_id,customer_name,address1,address2,town,county,post_code,country,fax,telephone,contact_name,email from customer");
    rs.next();
    firstCustomer = loadCustomer();
    return firstCustomer;
    public Customer getLastCustomer() throws SQLException{
    Customer lastCustomer;
    rs.last();
    lastCustomer = loadCustomer();
    return lastCustomer;
    public Customer getNextCustomer()throws SQLException{
    Customer nextCustomer ;
    if (rs.next()){
    nextCustomer = loadCustomer();
    else{
    nextCustomer = null;
    return nextCustomer;
    public Customer getPreviousCustomer()throws SQLException{
    Customer previousCustomer;
    if (rs.previous()){
    previousCustomer = loadCustomer();
    else
    previousCustomer = null;
    return previousCustomer;
    public Customer findCustomer(int inCustNum) throws SQLException{
    Customer foundCust;
    if (inCustNum==0){
    foundCust = getFirstCustomer();
    else{
    stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmt.executeQuery("select customer_id,customer_name,address1,address2,town,county,post_code,country,fax,telephone,contact_name,email from customer where customer_id = "+inCustNum);
    if (rs.next()){
    foundCust = loadCustomer();
    else
    foundCust = null;
    return foundCust;
    public Customer addCust()throws SQLException{
    Statement stmt2 = con.createStatement();
    ResultSet rsadd = stmt2.executeQuery("select custid.nextval from dual");
    rsadd.next();
    int id = rsadd.getInt("nextval");
    rsadd.close();
    stmt2.close();
    Customer newCust = new Customer(id);
    return newCust;
    public Customer saveCustomer(Customer inSaveCust)throws SQLException{
    Statement stmt3 = con.createStatement();
    int rowNum;
    //int incid = inSaveCust.getCid();
    if (inSaveCust.isNewCustomer()){
    stmt3.executeUpdate("insert into customer values ("
    +inSaveCust.getCustomer_id()
    +",'"+inSaveCust.getCustomer_name()
    +"','"+inSaveCust.getAddress1()
    +"','"+inSaveCust.getAddress2()
    +"','"+ inSaveCust.getTown()
    +"','"+ inSaveCust.getCounty()
    +"','"+inSaveCust.getPost_code()
    +"','"+inSaveCust.getCountry()
    +"','"+inSaveCust.getFax()
    +"','"+ inSaveCust.getTelephone()
    +"','"+inSaveCust.getContact_name()
    +"','"+inSaveCust.getEmail()+"')");
    inSaveCust = getFirstCustomer();//refreshes list after insert
    inSaveCust = getLastCustomer();// goes to the inserted record ie last one
    else {
    rowNum = rs.getRow();//traps the record number so can be returned to
    stmt3.executeUpdate("update customer set customer_name = '"+inSaveCust.getCustomer_name()
    + "', address1 = '"+inSaveCust.getAddress1()
    + "', address2 = '"+inSaveCust.getAddress2()
    + "', town = '"+ inSaveCust.getTown()
    + "', county = '"+ inSaveCust.getCounty()
    + "', post_code = '"+inSaveCust.getPost_code()
    + "', telephone = '"+inSaveCust.getCountry()
    + "', fax = '"+inSaveCust.getFax()
    + "', country = '"+inSaveCust.getTelephone()
    + "', contact_name = '"+inSaveCust.getContact_name()
    + "', email = '"+inSaveCust.getEmail()
    +"' where customer_id = "+inSaveCust.getCustomer_id());
    inSaveCust = getFirstCustomer();
    rs.absolute(rowNum); // points back to same record number as updated
    inSaveCust = loadCustomer();
    con.commit();
    return inSaveCust;
    //Trying to add in the delete method here(as u can see it is not working)
    /*public Customer deleteCustomer() throws SQL Exception {
    stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    rs = stmt4.executeQuery("delete from customer where customer_id = "Integer.parseInt(textCustomer_id.getText()));
    rs.next();
    firstCustomer = loadCustomer();
    return firstCustomer;
    public boolean isFirst() throws SQLException{
    return rs.isFirst();
    public boolean isLast() throws SQLException{
    return rs.isLast();
    public Customer loadCustomer ()throws SQLException{
    Customer cust = new Customer(rs.getInt("customer_id"),rs.getString("customer_name"),rs.getString("address1"),
    rs.getString("address2"),rs.getString("town"),rs.getString("county"),
    rs.getString("post_code"),rs.getString("country"),rs.getString("fax"),
    rs.getString("telephone"),rs.getString("contact_name"),rs.getString("email"));
    return cust;
    customerForm class
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.util.*;
    public class CustomerForm extends JFrame implements ActionListener {
    private Customer currentCustomer;
    private CustomerList inCustomerList;
    private JPanel panel;
    private JTextField textCustomer_id,textCustomer_name,textAddress1,textAddress2,textTown,
    textCounty,textPost_code,textCountry,textTelephone,textFax,textContact_name,textEmail,textFind;
    private JButton nextCust, prevCust,firstCust,lastCust,newCust,
    findCust,add,save,delete,jobs,close,deleteCust;
    public CustomerForm(CustomerList inC)throws SQLException{
    inCustomerList = inC;
    currentCustomer = inCustomerList.getFirstCustomer();
    displayForm();
    displayFields();
    setTextFields();
    displayButtons();
    getContentPane().add(panel);
    setVisible(true);
    public void displayForm() throws SQLException{
    setTitle("Customer Form");
    setSize(700,500);
    // Center the frame
    Dimension dim = getToolkit().getScreenSize();
    setLocation(dim.width/2-getWidth()/2, dim.height/2-getHeight()/2);
    getContentPane().setLayout(new BorderLayout());
    Border etched = BorderFactory.createEtchedBorder();
    panel = new JPanel();
    panel.setLayout( null );
    Border paneltitled = BorderFactory.createTitledBorder(etched,"");
    panel.setBorder(paneltitled);
    panel.setBackground(new Color(224,224,255));
    public void displayFields() throws SQLException{
    int x = 10;
    int y = 50;
    int textheight = 20;
    int textwidth = 150;
    int labelwidth = 110;
    int ydist = textheight + 10;
    int xdist = textwidth*2;
    JLabel labelCustomer_id = new JLabel("Customer Number:");
    labelCustomer_id.setBounds( x, y, labelwidth, textheight);
    panel.add(labelCustomer_id);
    JLabel labelCustomer_name = new JLabel("Customer Name:");
    labelCustomer_name.setBounds(xdist, y, labelwidth, textheight);
    panel.add(labelCustomer_name);
    JLabel labelAddress1 = new JLabel("Address 1:");
    labelAddress1.setBounds( x, y+ydist, labelwidth, textheight);
    panel.add(labelAddress1);
    JLabel labelAddress2 = new JLabel("Address 2:");
    labelAddress2.setBounds( xdist, y+ydist, labelwidth, textheight);
    panel.add(labelAddress2);
    JLabel labelTown = new JLabel("Town:");
    labelTown.setBounds(x, y+ydist*2, labelwidth, textheight);
    panel.add(labelTown);
    JLabel labelCounty = new JLabel("County:");
    labelCounty.setBounds(xdist, y+ydist*2, labelwidth, textheight);
    panel.add(labelCounty);
    JLabel labelPost_code = new JLabel("Post Code:");
    labelPost_code.setBounds(x, y+ydist*3, labelwidth, textheight);
    panel.add(labelPost_code);
    JLabel labelCountry = new JLabel("Country:");
    labelCountry.setBounds(xdist, y+ydist*3, labelwidth, textheight);
    panel.add(labelCountry);
    JLabel labelTelephone = new JLabel("Phone:");
    labelTelephone.setBounds(x, y+ydist*4, labelwidth, textheight);
    panel.add(labelTelephone);
    JLabel labelFax = new JLabel("Fax:");
    labelFax.setBounds(xdist, y+ydist*4, labelwidth, textheight);
    panel.add(labelFax);
    JLabel labelContact_name = new JLabel("Contact Name:");
    labelContact_name.setBounds(x, y+ydist*5, labelwidth, textheight);
    panel.add(labelContact_name);
    JLabel labelEmail = new JLabel("E-mail address:");
    labelEmail.setBounds(xdist, y+ydist*5, labelwidth, textheight);
    panel.add(labelEmail);
    JLabel labelFind = new JLabel("Customer Number Search:");
    labelFind.setBounds( 40, 360, 200, textheight);
    panel.add(labelFind);
    textAddress1 = new JTextField();
    textAddress1.setBounds(x+labelwidth, y+ydist, textwidth, textheight);
    panel.add(textAddress1);
    textAddress2 = new JTextField();
    textAddress2.setBounds(xdist+labelwidth, y+ydist, textwidth, textheight);
    panel.add(textAddress2);
    textTown = new JTextField();
    textTown.setBounds(x+labelwidth, y+ydist*2, textwidth, textheight);
    panel.add(textTown);
    textCounty = new JTextField();
    textCounty.setBounds(xdist+labelwidth, y+ydist*2, textwidth, textheight);
    panel.add(textCounty);
    textPost_code = new JTextField();
    textPost_code.setBounds(x+labelwidth, y+ydist*3, textwidth, textheight);
    panel.add(textPost_code);
    textCountry = new JTextField();
    textCountry.setBounds(xdist+labelwidth, y+ydist*3, textwidth, textheight);
    panel.add(textCountry);
    textTelephone = new JTextField();
    textTelephone.setBounds(x+labelwidth, y+ydist*4, textwidth, textheight);
    panel.add(textTelephone);
    textFax = new JTextField();
    textFax.setBounds(xdist+labelwidth, y+ydist*4, textwidth, textheight);
    panel.add(textFax);
    textContact_name = new JTextField();
    textContact_name.setBounds(x+labelwidth, y+ydist*5, textwidth, textheight);
    panel.add(textContact_name);
    textEmail = new JTextField();
    textEmail.setBounds(xdist+labelwidth, y+ydist*5, textwidth+50, textheight);
    panel.add(textEmail);
    textFind = new JTextField();
    textFind.setBounds(200, 360, 80, textheight);
    panel.add(textFind);
    textCustomer_id = new JTextField();
    textCustomer_id.setBounds(x+labelwidth, y, textwidth, textheight);
    panel.add(textCustomer_id);
    textCustomer_name = new JTextField();
    textCustomer_name.setBounds(xdist+labelwidth, y, textwidth+50, textheight);
    panel.add(textCustomer_name);
    public boolean delete() {
    textCustomer_id.setText("");
    textCustomer_name.setText("");
    textAddress1.setText("");
    textAddress2.setText("");
    textTown.setText("");
    textCounty.setText("");
    textPost_code.setText("");
    textCountry.setText("");
    textTelephone.setText("");
    textFax.setText("");
    textContact_name.setText("");
    textEmail.setText("");
    textFind.setText("");
    return true;
    public void displayButtons(){
    firstCust= new JButton("FIRST");
    firstCust.addActionListener(this);
    firstCust.setBounds(50, 430, 100, 20 );
    panel.add( firstCust );
    nextCust = new JButton("NEXT");
    nextCust.addActionListener(this);
    nextCust.setBounds(150, 430, 100, 20 );
    panel.add( nextCust );
    prevCust = new JButton("PREVIOUS");
    prevCust.addActionListener(this);
    prevCust.setBounds(250, 430, 100, 20 );
    panel.add( prevCust );
    lastCust= new JButton("LAST");
    lastCust.addActionListener(this);
    lastCust.setBounds(350, 430, 100, 20 );
    panel.add( lastCust );
    findCust= new JButton("FIND");
    findCust.addActionListener(this);
    findCust.setBounds(350, 360, 100, 20 );
    panel.add( findCust );
    add = new JButton("ADD");
    add.addActionListener(this);
    add.setBounds(150, 400, 100, 20 );
    panel.add( add );
    save = new JButton("SAVE");
    save.addActionListener(this);
    save.setBounds(250, 400, 100, 20 );
    panel.add( save );
    jobs = new JButton("JOBS");
    jobs.addActionListener(this);
    jobs.setBounds(550, 360, 100, 20 );
    panel.add( jobs );
    close = new JButton("CLOSE");
    close.addActionListener(this);
    close.setBounds(550, 430, 100, 20 );
    panel.add( close );
    delete = new JButton("DELETE");
    delete.addActionListener(this);
    delete.setBounds(350, 400, 100, 20 );
    panel.add( delete );
    deleteCust = new JButton("DELETECUST");
    deleteCust.addActionListener(this);
    deleteCust.setBounds(450, 400, 100, 20);
    panel.add( deleteCust );
    public void getTextFields(){
    currentCustomer.setCustomer_id(Integer.parseInt(textCustomer_id.getText()));
    currentCustomer.setCustomer_name(textCustomer_name.getText());
    currentCustomer.setAddress1(textAddress1.getText());
    currentCustomer.setAddress2(textAddress2.getText());
    currentCustomer.setTown(textTown.getText());
    currentCustomer.setCounty(textCounty.getText());
    currentCustomer.setPost_code(textPost_code.getText());
    currentCustomer.setCountry(textCountry.getText());
    currentCustomer.setFax(textFax.getText());
    currentCustomer.setTelephone(textTelephone.getText());
    currentCustomer.setContact_name(textContact_name.getText());
    currentCustomer.setEmail(textEmail.getText());
    public void setTextFields() throws SQLException{
    textCustomer_id.setText(String.valueOf(currentCustomer.getCustomer_id()));
    textCustomer_id.setEditable(false);
    textCustomer_name.setText(currentCustomer.getCustomer_name());
    textAddress1.setText(currentCustomer.getAddress1());
    textAddress2.setText(currentCustomer.getAddress2());
    textTown.setText(currentCustomer.getTown());
    textCounty.setText(currentCustomer.getCounty());
    textPost_code.setText(currentCustomer.getPost_code());
    textCountry.setText(currentCustomer.getCountry());
    textFax.setText(currentCustomer.getFax());
    textTelephone.setText(currentCustomer.getTelephone());
    textContact_name.setText(currentCustomer.getContact_name());
    textEmail.setText(currentCustomer.getEmail());
    public void actionPerformed(ActionEvent e) {
    Object source = e.getSource();
    try {
    if (source == nextCust)
    currentCustomer = inCustomerList.getNextCustomer();
    else if (source == prevCust)
    currentCustomer = inCustomerList.getPreviousCustomer();
    else if (source == findCust) {
    try {
    currentCustomer =
    inCustomerList.findCustomer(Integer.parseInt(textFind.getText()));
    catch (NumberFormatException ex) {
    JOptionPane.showMessageDialog(
    null, "Invalid Customer number", "ERROR",
    JOptionPane.ERROR_MESSAGE);
    if (currentCustomer == null) {
    JOptionPane.showMessageDialog(null, "Customer not found");
    currentCustomer = inCustomerList.getFirstCustomer();
    textFind.setText(null);
    else if (source == firstCust)
    currentCustomer = inCustomerList.getFirstCustomer();
    else if (source == lastCust)
    currentCustomer = inCustomerList.getLastCustomer();
    else if (source == add) {
    currentCustomer = inCustomerList.addCust();
    add.setEnabled(false);
    else if (source == delete) {
    delete();
    else if (source == save) {
    add.setEnabled(true);
    getTextFields();
    currentCustomer = inCustomerList.saveCustomer(currentCustomer);
    //else if (source == jobs) {
    // JFrame newJobForm = new JobForm(currentCustomer.getJobList());
    //else if (source == deleteCust) {
    //........... //currentCustomer = inCustomerList.deleteCustomer(currentCustomer);
    else if (source == close) {
    dispose();
    setTextFields();
    nextCust.setEnabled(!inCustomerList.isLast());
    prevCust.setEnabled(!inCustomerList.isFirst());
    firstCust.setEnabled(!inCustomerList.isFirst());
    lastCust.setEnabled(!inCustomerList.isLast());
    catch (SQLException ex) {
    System.out.println("Failed");
    System.out.println(ex.getMessage());
    ex.printStackTrace();
    System.exit(-1);
    PLEASE HELP ME!!!

    http://www.ss64.demon.co.uk/orasyntax/

  • Return Data from Oracle using a web service in AXIS - please help

    Hi Forum,
    I am very new to web services and Java tech. and recently I have been assigned to work with technology and I am struggling to learn it and need your help and assistance.
    I am trying to return some data from a an oracle database but I have to do that using a web service and I am using AXIS. For example below is a simple program that returns two columns for the demo EMP table
    import java.sql.*;
    class emp {
    public static void main(String args[])
    throws ClassNotFoundException, SQLException {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    // or you can use:
    // DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott", "tiger");
    Statement stmt = conn.createStatement( );
    ResultSet rset = stmt.executeQuery("select * from emp");
    while(rset.next( )) {
    System.out.println(rset.getString(1));
    System.out.println(rset.getString(2));
    rset.close( );
    stmt.close( );
    conn.close( );
    } but I do not know how to convert this into a web service.
    Please help.
    Thanks in advance.
    Regards,
    Ravi

    The following code returns Document. I will be calling the below function to convert my Resultset to document. In my JWS file i simply call a method with parameters. can a web service method in .jws file return Document type. It shows error will doing so. Please help me.
    public static Document toDocument(ResultSet rs) throws ParserConfigurationException, SQLException
              Document res_doc = null;
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              DocumentBuilder builder = factory.newDocumentBuilder();
              Document doc = builder.newDocument();
              Element results = doc.createElement("Results");
              doc.appendChild(results);
              ResultSetMetaData rsmd = rs.getMetaData();
              int colCount = rsmd.getColumnCount();
              while (rs.next())
              Element row = doc.createElement("Row");
              results.appendChild(row);
              for (int i = 1; i <= colCount; i++)
              String columnName = rsmd.getColumnName(i);
              Object value = rs.getObject(i);
              Element node = doc.createElement(columnName);
              node.appendChild(doc.createTextNode(value.toString()));
              row.appendChild(node);
              return res_doc;
         }

Maybe you are looking for

  • [SOLVED]failure to mount external usb drive, possible hardware malfu

    Please excuse me for posting this in the Arch forums, but I'd appreciate at least a point in the right direction. Every Google hit I came up with had a dubious solution like "reinstall USB drivers". I've never had an external drive fail on me yet, an

  • User Defined Object

    Hi, I'm trying do create the UDO object in the OWB(paris) and based on this definition generate the PL/SQL code. The first step, define and create UDO is clear and works as I expected. But the generation step is question for me. I see only one soluti

  • E-mailing photos from iPhoto

    When I go to Preferences, the only choices that "Mail using . . ." gives me is Mail or Microsoft Entourage. Is there any way that I could connect directly to gmail, my primary e-mail program? Thank you. Ricardo

  • Roll-up not possible - Help

    Hi, COPA delta load is successfully loaded in to the data target, some how i am getting the following error message and Roll up failed for the last two times. Roll-up not possible; no filled aggregates available Issue happend in Production, Could you

  • How do I combine projects that are currently on different computers?

    I am teaching a TV production class with virtually no knowledge of Premiere Pro.  I have students working at four Mac stations.  Is there a way to combine the four projects into one?