What exactly is this code doing?

Our prof gave us some sample code for converting Person objects into array information, and back again.
My question is about this method:
public Person[] convertToPersonObjects()
  Person p[] = new Person[data.size()];
  for(int i = 0; i < p.length; i++)
     p[i] = new Person((String)((Vector)data.elementAt(i)).elementAt(0),
            (String)((Vector)data.elementAt(i)).elementAt(1),
            (String((Vector)data.elementAt(i)).elementAt(2),
            (String)((Vector)data.elementAt(i)).elementAt(3),
            (String)((Vector)data.elementAt(i)).elementAt(4));
  return p;
}"data" is a vector that has been holding the five attributes of Person. What I'm not getting here is why he used this construction: ((Vector)data.elementAt(i)).elementAt(1)So is this casting the Vector value of the "data" vector element into a String that is then stored as element 1, 2, etc. of the Person object? Why would a vector element have to be cast into a Vector anyway? And I'm confused by the double use of "elementAt".
Help is much appreciated!

((Vector)data.elementAt(i)).elementAt(1)Hi!, I think that your data Vector contains in every posotion another Vector with the elements of each person, so if the position i of Data has a Vector you should cast what elemenAt returns and then acces what you need to create a Person Object.
Search your source code for something like "data.add();" and see if it adds a Vector to data.
The cast to String is done because the elementAt method returns an Object
Hope it helps

Similar Messages

  • Can you tell me what this code does?

    Can you tell me what this code does?
    import java.io.*;
    class Assignment1
    public static String[][] tdi = {     {"Paris", "418", "Rome", "55"},
                             {"Liverpool", "121", "Copenhagen", "35"},
                             {"Liverpool", "418", "Paris", "50"},
                             {"Liverpool", "553", "Frankfurt", "55"},
                             {"Frankfurt", "553", "Budapest", "50"},
                             {"Amsterdam", "121", "Madrid", "65"},
                             {"Amsterdam", "418", "Paris", "35"},
                             {"Madrid", "121", "Stockholm", "90"},
                             {"Budapest", "553", "Warsaw", "30"},
                             {"Copenhagen", "121", "Amsterdam", "35"},
                             {"Rome", "418", "Amsterdam", "60"},
    //--Start Method--
    public static void main( String args[] ) throws IOException
    System.out.println("Welcome to NoWings Airline.");
    InputStreamReader input = new InputStreamReader(System.in);
    BufferedReader keyboardInput = new BufferedReader(input);
    System.out.println("Please enter the airport you wish to depart from:");
    String[] info = TDIDLL.searchDest( keyboardInput.readLine() );
    if (info == null)
    System.out.println("Sorry, no plane to this destination");
    else
    System.out.println(info[0]+" departing at platform "+info[1]); }}
    public static String[] searchDest( String dest )
    String[] result = null;
    for(int i = 0; i < tdi.length; i++)
         if (tdi[1].equals(dest)) {
         result = new String[2];
         result[0] = tdi[i][0];
         result[1] = tdi[i][2];
         return result;
    return result; }
    // Info Method //
    // Fly Method //
    // Exit Method //
    Thanks. Also, can you tell me where I have gone wrong in the code.
    Much appreciated.

    Can you tell me what this code does?Why don't you run it and find out for yourself?

  • What this code does ?

    what this code does ?
    System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");

    i am studying this code....
    //Verify the hostname, check all trusted cetifcates and install them in the machine
                             com.sun.net.ssl.HostnameVerifier ver = new com.sun.net.ssl.HostnameVerifier(){
                                  public boolean verify(String urlHostname,String certHostname)
                                       try
                                                                {  return true;
                                       } catch(Exception x){ return true; }
                             javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[]{
                                  new javax.net.ssl.X509TrustManager() {
                                       public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                                            return null;
                                       public void checkClientTrusted(
                                            java.security.cert.X509Certificate[] certs, String authType) {
                                       public void checkServerTrusted(
                                            java.security.cert.X509Certificate[] certs, String authType) {
                             // Install the all-trusting trust manager
                             try {
                                  javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
                                  sc.init(null, trustAllCerts, new java.security.SecureRandom());
                                  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                                  sc=null;
                             } catch (Exception e) {
                                  e.printStackTrace();
                             //Setting the defaultHost name verfier set by the user for communication
                             HttpsURLConnection.setDefaultHostnameVerifier(ver);/**/please note the bold colored code from the above i.e
    HttpsURLConnection.setDefaultHostnameVerifier(ver);
    so, ver instance has been presented to the setDefaultHostnameVerifier . fine....but who is calling the methods verify() which is described in the implemented Annoynymous interface HostnameVerifier .
    who is calling that overridden method verify() ?
    similarly, who is calling getAcceptedIssuers() method?
    I DONT see any invocation of these overridden methods .
    are these methods are FRAUD and BUGGY...and are not needed in this code....are they redundant ?
    OR are these methods are invoked by the HttpsURLConnection internally somehow....
    confused about the functionng of this code.
    thanks for the time

  • What exactly continue & return statement does

    Hi All,
    Here i what to know what exactly continue & return statement does?Pls. do explain with an example for each.
    Thanx,
    M.Ananthu

    In this example, break would do the same thing that return does.
    import java.awt.*;
    import javax.swing.*;
    public class demo {
      static String[] strings = {
        "", "Mary", "had", "", "a", "test", "little", "lamb"
      public static void main(String[] args) {
        for(int j = 0; j < strings.length; j++) {
          if(strings[j].equals(""))
            continue;
          System.out.println(strings[j] + " ");
          if(strings[j].equals("test"))
            return;
    }

  • In the second step of bootcamp, I am supposed to either check the box where it says create a windows install disk, what exactly is this? Do I need to do this?

    In the second step of bootcamp, I am supposed to either check the box where it says create a windows install disk, what exactly is this? Do I need to do this? I have a windows 7 install disk, but I don't know what this means.

    If you already have Windows on a DVD or USB drive, you don't have to tick that option. That's only for people who have Windows on a ISO file and have to burn it into a USB drive

  • What is the flollowing code doing?

    What is the flollowing code doing? What do the %2 %3 %4 %5 %6 %7 stand for?
    java %COH_OPTS% -Xms1g -Xmx1g -Xloggc: com.tangosol.net.DefaultCacheServer %2 %3
    %4 %5 %6 %7

    %2 would need to be the path to the "cache-config.dtd" compliant configuration file.
    %3 the interval in second to check the service status.
    The rest would be ignored.
    For Example:
    java -server -Xms512m -Xmx512m com.tangosol.net.DefaultCacheServer coherence-cache-config.xml 5
    Re: What is the flollowing code doing?
    Thanks,
    Everett Williams
    Coherence Team
    Edited by: ewilliams on Aug 26, 2009 2:36 PM

  • My iphone 4 automatically shuts down , twice it has happened though it starts by holding the home screen and sleep button for 10 seconds but what exactly causes this problem? some defect in my set?

    My iphone 4 automatically shuts down , twice it has happened though it starts by holding the home screen and sleep button for 10 seconds but what exactly causes this problem? some defect in my set?

    do you hold the home and sleep button?

  • Contest: Guess whats wrong with this code!

    Can you guess whats wrong with this code snippet? Perhaps its too easy...
    private void clearDefaultTableModel( DefaultTableModel dtm) {    
            int  rowCount  = dtm.getRowCount();
            for(int i =0;  i < rowCount; i++) {
                dtm.removeRow(i);  
        }- Karl XII

    Can you guess whats wrong with this code snippet?
    Perhaps its too easy...
    private void clearDefaultTableModel(
    DefaultTableModel dtm) {    
    int  rowCount  = dtm.getRowCount();
    for(int i =0;  i < rowCount; i++) {
    dtm.removeRow(i);  
    it should be
    private void clearDefaultTableModel(DefaultTableModel dtm) {    
       int  rowCount  = dtm.getRowCount();
       for(int i =0;  i < rowCount; i++) {
         dtm.removeRow(0);  
    }or another way
    private void clearDefaultTableModel(DefaultTableModel dtm) {    
      while(dtm.getRowCount()>0){
         dtm.removeRow(0);  

  • What exactly the "recovery disc" does?

    I'm about to reinstall everything on my laptop but would like to know what exactly the "recovery disc" does....
    I presume that it formats the HDD with a clean install of the OS and that all the toshiba apps like disc recorder, VAP etc... are NOT installed and have to be installed afterwards??

    > {quote:title=Jayjay wrote:}{quote}
    > Well, the recovery CD contains a Toshiba image. The Toshiba image is a package and is contains a Windows OS, Toshiba drivers, tools and additional software.
    > Simply said it contains everything what you could find preinstalled on the Toshiba notebook.
    >
    > And Yes; the recovery CD formats the whole HDD (also the partitions) and installs everything again.
    > It sets the notebook back to the factory settings
    so its just the OS packed with toshiba software and drivers - guess i wont have to download all of the toshiba applicaitions just yet then :)

  • Please explain what does this code does exactly

    Can any one explain me what does the below code does.
    This is the code written in one of the BADI (ME_PO_PRICING_CUST) .This badi will be triggered when a sales order delivery address is changed and while saving it this will be triggered. Over all what i come to know is they re trigerring a new version in this code. Can anyone explain me what exactly they are doing in this.Thanks...
    METHOD IF_EX_ME_PO_PRICING_CUST~PROCESS_KOMK.
      FIELD-SYMBOLS: <EKKO> TYPE ANY,
                     <PROCSTAT> TYPE MEPROCSTATE,
                     <FRGKE> TYPE FRGKE,
                     <YNAST> TYPE TABLE,
                     <WA_YNAST> TYPE NAST.
      IM_EKKO-PROCSTAT = 02.
    *break-point.
      ASSIGN ('(SAPLMEPO)EKKO') TO <EKKO>.
      ASSIGN ('(SAPLMEPO)YNAST[]') TO <YNAST>.
      IF <EKKO> IS ASSIGNED.
        ASSIGN COMPONENT 'PROCSTAT' OF STRUCTURE <EKKO> TO <PROCSTAT>.
        ASSIGN COMPONENT 'FRGKE' OF STRUCTURE <EKKO> TO <FRGKE>.
        IF <FRGKE> = 'R'.
          <PROCSTAT> = '02'.
        ENDIF.
      ENDIF.
      IF <YNAST> IS ASSIGNED.
        IF <FRGKE> = 'R'.
          LOOP AT <YNAST> ASSIGNING <WA_YNAST>.
            <WA_YNAST>-AKTIV = 'X'.
          ENDLOOP.
        ENDIF.
      ENDIF.
    ENDMETHOD.

    r_htkl must be a range table. check the declaration part of it.
    p_htkl is a parameter on selection screen i hope.
    so, there are four fields on a range table.(range table are similar to your select options)
    1. SIGN ( I or E  - Inclusive or Exculsive)
    2. OPTION(options like EQ = euqal, BT = Between, CP = contains pattern etc)
    3. LOW (value)
    4. HIGH (value)
    so..
    IF NOT p_htkl IS INITIAL. " checks if some thing is being passed to the parameter
    r_htkl-sign='I'. " give the sign a value I i.e it make inclusive sign
    r_htkl-option='EQ'. " EQ to option means you value will be checked for a equal to condition
    r_htkl-low=p_htkl. " the low field in now assigned the same value of the parameter p_hktl
    APPEND r_htkl. " the range table is appended.
    endif.
    so this range table can be used in select statements as :
    select * from abcd into gt where xyz in r_hktl. ==> this will check for a EQ condition with value in r_hktl-low in database or
    in if statements like : if abc in r_hktl. ==> this will check the EQ condition of abc with the r_hktl-low.
    Had it been
    r_htkl-sign='E'.
    then the condition is same but with a NOT.. that means NOT EQ or NOT BT etc.
    as exclusive of the option.
    etc.
    hope this is clear.
    AND PLEASE CLOSE THE OTHER THREAD (duplicate)

  • HELP PLEASE - WHATS WRONG WITH THIS CODE

    Hi. I get this message coming up when I try to compile the code,
    run:
    java.lang.NullPointerException
    at sumcalculator.SumNumbers.<init>(SumNumbers.java:34)
    at sumcalculator.SumNumbers.main(SumNumbers.java:93)
    Exception in thread "main"
    Java Result: 1
    BUILD SUCCESSFUL (total time: 2 seconds)
    I am not sure whats wrong with the code. Any assistance would be nice. The code is below.
    package sumcalculator;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SumNumbers extends JFrame implements FocusListener {
    JTextField value1;
    JTextField value2;
    JLabel equals;
    JTextField sum;
    JButton add;
    JButton minus;
    JButton divide;
    JButton multiply;
    JLabel operation;
    public SumNumbers() {
    SumNumbersLayout customLayout = new SumNumbersLayout();
    getContentPane().setFont(new Font("Helvetica", Font.PLAIN, 12));
    getContentPane().setLayout(customLayout);
    value1.addFocusListener(this);
    value2.addFocusListener(this);
    sum.setEditable(true);
    value1 = new JTextField("");
    getContentPane().add(value1);
    value2 = new JTextField("");
    getContentPane().add(value2);
    equals = new JLabel("label_1");
    getContentPane().add(equals);
    sum = new JTextField("");
    getContentPane().add(sum);
    add = new JButton("+");
    getContentPane().add(add);
    minus = new JButton("-");
    getContentPane().add(minus);
    divide = new JButton("/");
    getContentPane().add(divide);
    multiply = new JButton("*");
    getContentPane().add(multiply);
    operation = new JLabel();
    getContentPane().add(operation);
    setSize(getPreferredSize());
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public void focusGained(FocusEvent event){
    try {
    float total = Float.parseFloat(value1.getText()) +
    Float.parseFloat(value2.getText());
    sum.setText("" + total);
    } catch (NumberFormatException nfe) {
    value1.setText("0");
    value2.setText("0");
    sum.setText("0");
    public void focusLost(FocusEvent event){
    focusGained(event);
    public static void main(String args[]) {
    SumNumbers window = new SumNumbers();
    window.setTitle("SumNumbers");
    window.pack();
    window.show();
    class SumNumbersLayout implements LayoutManager {
    public SumNumbersLayout() {
    public void addLayoutComponent(String name, Component comp) {
    public void removeLayoutComponent(Component comp) {
    public Dimension preferredLayoutSize(Container parent) {
    Dimension dim = new Dimension(0, 0);
    Insets insets = parent.getInsets();
    dim.width = 711 + insets.left + insets.right;
    dim.height = 240 + insets.top + insets.bottom;
    return dim;
    public Dimension minimumLayoutSize(Container parent) {
    Dimension dim = new Dimension(0, 0);
    return dim;
    public void layoutContainer(Container parent) {
    Insets insets = parent.getInsets();
    Component c;
    c = parent.getComponent(0);
    if (c.isVisible()) {c.setBounds(insets.left+24,insets.top+48,128,40);}
    c = parent.getComponent(1);
    if (c.isVisible()) {c.setBounds(insets.left+256,insets.top+48,128,40);}
    c = parent.getComponent(2);
    if (c.isVisible()) {c.setBounds(insets.left+408,insets.top+48,56,40);}
    c = parent.getComponent(3);
    if (c.isVisible()) {c.setBounds(insets.left+488,insets.top+48,152,40);}
    c = parent.getComponent(4);
    if (c.isVisible()) {c.setBounds(insets.left+128,insets.top+136,72,40);}
    c = parent.getComponent(5);
    if (c.isVisible()) {c.setBounds(insets.left+248,insets.top+136,72,40);}
    c = parent.getComponent(6);
    if (c.isVisible()) {c.setBounds(insets.left+368,insets.top+136,72,40);}
    c = parent.getComponent(7);
    if (c.isVisible()) {c.setBounds(insets.left+488,insets.top+136,72,40);}
    c = parent.getComponent(8);
    if (c.isVisible()) {c.setBounds(insets.left+176,insets.top+48,56,40);}
    }

    Thank you. How do i amend this? I have defined value1though.Yes, you did - but after the call to addFocusListener(...). It needs to be before it.
    BTW, you did the same thing with "value2.addFocusListener(this)" and "sum.setEditable(true)" on the next two lines. You're attempting to call a method on an object that doesn't exist yet (i.e., you haven't called new yet).

  • Whats Wrong with this code? URLReader

    Ok, so I have this URLReader.java program. It goes to a specific website, I put in a project ID. It pulls up a project. I can then "Scrape", "Extract Data from the URL and put them into variables. I then upload the variables into the DB.
    I've used this code over and over again and it works, but I seem to have a problem with the second part of the code.The error message that I get is:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    Please note the URL is a fake one. I did not want to give the real URL. I have provided the String to read, which is actually HTML code. I thought it might be the "Researchers(s):" string that it does like, maybe a problem with "(s), but I dont know?
    First part of the code: This really gets a project ID from a collection and iterates throught the collection with each project ID.
    String projectId = "87023";
                java.net.URL projectDetails = new  java.net.URL("http://someSite.com/portfolio/ProjectDetails.asp?Source=Tracking&Key="+projectId);
                java.io.BufferedReader in =
                            new java.io.BufferedReader(new java.io.InputStreamReader(projectDetails.openStream()));
                String projDetailspage = new String("");
                String inputLine = "";
                while ((inputLine = in.readLine()) != null)
                    projDetailspage = projDetailspage.concat(inputLine.trim());
                System.out.println("project ID: "+ projectId);
    Second Part of the Code:
    String str = (projDetailspage.split("\\<[Bb]\\>Researcher(s)\\</[Bb]\\>")  //  look for: <b>Researcher(s):</b> , also the part of code I am having problems with.
                [1].split( "\\<td\\>")[1].split("\\</table>")[0].trim());   //put everything into a variable call str from the <td> to the </table> tags 
                System.out.println("String before replace all: "+ str);
    The HTML code to read and search through:<!-- researchers -->
        <tr>
              <td width="30%" align="right" valign="top">
                   <font size="-1">
                   <b>Researcher(s):</b>
                   </font>
              </td>
                  <td width="70%" align="left" valign="top">
                        <font size="-1">
                        Dr. Michael E. Welge, University of Illinois at Urbana-Champaign
                        </font>
                   </td>
                   </tr>
                            <tr>
                                  <td width="30%">
                                       <font size="-1">
                                       </font>
                                  </td>
                                <td width="70%" align="left" valign="top">
                                       <font size="-1">
                                       Dr. Albert J. Valocchi, University of Illinois at Urbana-Champaign
                                       </font>
                                  </td>
                            </tr>
                            <tr>
                                  <td width="30%">
                                       <font size="-1">
                                       </font>
                                  </td>
                                <td width="70%" align="left" valign="top">
                                       <font size="-1">
                                       Dr. Barbara Ann Bailey, University of Illinois at Urbana-Champaign
                                       </font>
                                  </td>
                            </tr>
                            <tr>
                                  <td width="30%">
                                       <font size="-1">
                                       </font>
                                  </td>
                                <td width="70%" align="left" valign="top">
                                       <font size="-1">
                                       Dr. David E. Goldberg, University of Illinois at Urbana-Champaign
                                       </font>
                                  </td>
                            </tr>
         <!-- students -->
        <tr>
              <td width="30%" align="right" valign="top">
                   <font size="-1">
                   <b>Student(s):</b>
                   </font>
              </td>
                   <td width="70%" align="left" valign="top">
                        <font size="-1">
                        None Found
                        </font>
                   </td>
              </tr>
              </table>
              </td>
         </tr>
         </table>
         </td>
    </tr>
    </table>

    camickr
    I ran your program and it works great. This is the output I get. This is for a project that had 4 researchers, that is not always the case.
    investigator1 = r. Michael E. Welge
    investigator2 = Dr. Albert J. Valocchi
    investigator3 = Dr. Barbara Ann Bailey
    investigator4 = Dr. David E. Goldberg
    for some reason I loose the D in Dr. for the first Investigator.
    also, I know I need to modify my code to find out how many researchers there are. I then place them into the correct variable.
    example
    researchers String that your code works on: None Found</font></td></tr><!-- students --><tr><td width="30%" align="right" valign="top"><font size="-1"><b>Student(s):</b></font></td><td width="70%" align="left" valign="top"><font size="-1">Dr. Terry Hogan, Pennsylvania State University</font></td></tr><tr><td width="30%"><font size="-1"></font></td><td width="70%" align="left" valign="top"><font size="-1">Dr. Chengyu Shen, Pennsylvania State University</font></td></tr><tr><td width="30%"><font size="-1"></font></td><td width="70%" align="left" valign="top"><font size="-1">Dr. Anne Pifer, Pennsylvania State University</font></td></tr>
    investigator1 = one Found|Student(s):|Dr. Terry Hogan  // should be None Found.
    investigator2 = Dr. Chengyu Shen
    investigator3 = Dr. Anne Pifer
    npe errorjava.lang.ArrayIndexOutOfBoundsException: 3
    The logic should be, when I scrape between tags, if it should be "None Found" then skip to the next project ID , also, each project may have as many as 0, 1, 2, 3, 4 researchers. but no more than 4
    So I thought of doing an:
    If( researchers == 2)
        investigator1 = investigator[x];
        investigator2 = investigator[x];
    }etc...
    Thanks again.
    if you need me to email you the code. my email addres is [email protected]
    I know I am not that talented of a programmer, but I am learning, and trying all the time. I want to do this the correct way, but I am not always sure which way that is. I usually try a class Diagram and go from there, but I have had some trouble with this one. If you need more of an explanation then email me.
    orozcom

  • Can understand whats wrong with this code.

    I'm sort new to Java programing, and I created this simple converter, but when I try to complie it, it gives me an exception error, could some one tell me how to correct this code.
    import java.text.*;
    import javax.swing.*;
    public class Converter
         private final static double EURO = .8295577, YEN = 115.614, CAD = 1.17781;
         public static void main (String[] args)
               String input =null;
               double US= 0.0;
               DecimalFormat twoPrecision = new DecimalFormat("0.00");
             input() = 0
              try{
                   US = Double.parseDouble (input);
                    System.out.print("US to Euro: ");
                    System.out.println(twoPrecision.format(US * EURO));
                  US = Double.parseDouble (input);
                    System.out.print("US to Yen: ");
                    System.out.println(twoPrecision.format(US * YEN));
                  US = Double.parseDouble (input);
                    System.out.print("US to Cad: ");
                    System.out.println(twoPrecision.format(US * CAD));
              catch(NumberFormatException e)
                   JOptionPane.showMessageDialog(null,
                                    "You must enter a number",
                                    "Input data error",
                                    JOptionPane.ERROR_MESSAGE);
    }

    Try this:
    import java.text.*;
    import javax.swing.*;
    import java.io.*;
    public class Converter
         private final static double EURO = .8295577, YEN = 115.614, CAD = 1.17781;
         public static void main (String[] args)
               double US= 0.0;
               DecimalFormat twoPrecision = new DecimalFormat("0.00");
               try{
                   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
             String input=br.readLine();
                   US = Double.parseDouble (input);
                    System.out.print("US to Euro: ");
                    System.out.println(twoPrecision.format(US * EURO));
                  US = Double.parseDouble (input);
                    System.out.print("US to Yen: ");
                    System.out.println(twoPrecision.format(US * YEN));
                  US = Double.parseDouble (input);
                    System.out.print("US to Cad: ");
                    System.out.println(twoPrecision.format(US * CAD));
              catch(Exception e)
                   JOptionPane.showMessageDialog(null,
                                    "You must enter a number",
                                    "Input data error",
                                    JOptionPane.ERROR_MESSAGE);
    }

  • Whats wrong in this code using ODBC interface of T10 in C ?

    Hi!
    I am trying to connect TimesTen using ODBC in a C application, I am trying to use the dynamic binding of parameters the query. The problem is elaborated in the code. In the comments.
    #include <windows.h>
    #include <sql.h>
    #include <sqlext.h>
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    int main()
    SQLRETURN rc = SQL_SUCCESS;
    /* General return code for the API */
    SQLHENV hEnv = SQL_NULL_HENV;
    /* Environment handle */
    SQLHDBC hDbc = SQL_NULL_HDBC;
    /* Connection handle */
    SQLHSTMT hStmt = SQL_NULL_HSTMT;
    /* Statement handle */
    SQLCHAR ConnOut[255];
    /* Buffer for completed connection string */
    SQLSMALLINT connOutLen;
    /* number of bytes returned in ConnOut */
    SQLCHAR ConnString = (SQLCHAR ) "DSN=testTT;PWD=spideradm;";
    /* Connection attributes */
    rc = SQLAllocEnv(&hEnv);
    if (rc != SQL_SUCCESS) {
    fprintf(stderr,"Unable to allocate an environment handle\n");
    exit(1);
    SQLINTEGER param1 = 0;
    SQLINTEGER paramstatus = 0;
    rc = SQLAllocConnect(hEnv, &hDbc);
    rc = SQLDriverConnect(hDbc, NULL,ConnString, SQL_NTS,ConnOut, 255,&connOutLen,SQL_DRIVER_NOPROMPT);
    hStmt = SQL_NULL_HSTMT;
    rc = SQLAllocStmt(hDbc, &hStmt);
    rc = SQLPrepare(hStmt,(SQLCHAR*) "select * from test where recno = ? ",SQL_NTS);
    rc = SQLBindParameter(hStmt,1,SQL_PARAM_INPUT,SQL_C_SHORT,SQL_INTEGER,0,0,¶m1,0,¶mstatus);
    param1= 1;
    rc = SQLExecute(hStmt); // here it goes very perfect
    param1 = 2;
    rc = SQLExecute(hStmt); // here is the problem it returns -1
    }

    There are (at least) 3 problems with this code:
    1. The error checking after each ODBC call is far too simplistic. Whenever an ODBC call returns something other than SQL_SUCCESS then you need to call the SQLError() function (multiple times in a loop until it returns SQL_NO_DATA) to retrieve the error or warning information which you should then report. If you do that then the error information would give you a clue to the problem.
    2. The parameter variable 'param1' is declared as a SQLINTEGER (32-bit integer) but you bind it in the SQLBindParameter() call as a SQL_C_SHORT. This is incorrect and will likely cause problems. It should be bound as a SQL_C_SLONG.
    3. When you execute a statement that retrieves data (such as the SELECT statement in your example) a cursor is created. The cursor remains open until (a) you explicitly close it with SQLFreeStmt(hStmt, SQL_CLOSE), or (b) you do a commit or rollback (which closes all open cursors on the connection).
    Your problem here is that the first SQLExecute opens a cursor for hStmt but you then do not fetch any data or close the cursor. When you try the second execute you get an error as there is already an open cursor for that statement. If you had used SQLError(0 to retrieve and report the error codes and messages you would see that you had incurred either an 'INVALID CURSOR STATE' or 'FUNCTION SEQUENCE ERROR' error.
    The fix is to insert the call:
    SQLFreeStmt(hStmt,SQL_CLOSE);
    after the each SQLExecute(0 call. Of course, in a real application there would also be a SQLFetch() loop first to retrieve and process the results of the query.
    Chris

  • Fed up! dont know whats wrong with this code

    import java.io.*;
    import java.net.*;
    import java.awt.*;
    public class machine {
         private String machine_name;
         private String IP_address;
         public static void main(String[] args) throws IOException {
                   machine server = new machine();
                   server.machine_name = "SERVER1";
                   server.IP_address   = "192.168.0.1";
                   InputStreamReader reads_incoming = null;
                   // Reads incoming Bytes
                   PrintWriter sends_outgoing = null;
                   Socket ping_socket         = null;
                   try{
                        ping_socket = new Socket(server.machine_name , 7);
                        sends_outgoing = new PrintWriter(ping_socket.getOutputStream(),true);
                        reads_incoming = new InputStreamReader(ping_socket.getInputStream());
                   catch (UnknownHostException e){
                        //report error to sole text box
                   catch (IOException e)
                        //similar
                   /* Need a string to send some arbitrary bytes to SERVER1
                    * using IP_address instead , as this field in this implementation
                   while(true)
                        sends_outgoing.println(server.IP_address);
                        if(ping_socket.getInputStream() != null)
                             System.out.print("Server is up");
    }

    same... i am not very experienced, and try and uses this as training... but as new to java programming i could still mention about 5 things that might be wrong with this code... so a deeper explanation would be nice...
    while(true) { } for example seems like a nice way to make infinite loop that can suck your memory out of your computer pretty fast :-) newb

Maybe you are looking for