Result.getString("column_name")

Hello All,
I was wondering which is the best practice when we are getting the result from a query :
result.getString("column_name") or result.getString("column_number")
Thanks

dof wrote:
DBA's changing table names? They should be fired.
It's the application developers who should control that.
Anyway, I use fieldName, because i might change the select and have different order.
This is actually a better reason for using the column number.
It is a best practice to fetch the column values in the order that they appear in the SELECT.
But there is no one "right" answer to this. The pros for each are as follows.
getXXX by String
- somewhat self documenting, see what field exactly you are getting (this is mitigated somewhat by not using SELECT * )
- as you mention if the result set changes (number or order of columns) this will not have to be changed as well
getXXX by int
- allows you to see that you are fetching columns in their natural order
- somewhat faster, this is admittedly small but with larger result sets (in terms of numbers of columns) may have some affect.

Similar Messages

  • DB: How to handle the value results.GetString("NAME")

    Hello.
    I'm trying to handle the value of a field from my DataBase:
    PreparedStatement sql = Conn.prepareStatement("SELECT NAME FROM MY_TABLE");
    ResultSet results = sql.executeQuery();
    String Name = results.GetString("NAME");
    out.println(myName);
    I'm able to display the value of 'myName' (Tom), but if try:
    if (myName.equals("Tom")) {...}
    or
    if (myName == "Tom") {...}
    There is no response.
    Does anybody have any experience?
    Thank you.

    hey,
    String myName = results.getString("NAME");
    then u can use
    if(myName.equals('Tom'){
    }else
    The above condition will be true if myName has Tom in it.. it has to be T o m . even if it is TOM or tOm or some other case it will never match.. if u are not bothered about the case then
    use
    if(myName.equalsIgnoreCase('Tom'){
    }else
    which will ignore case .
    hope this will help u ....
    Hello.
    I'm trying to handle the value of a field from my
    DataBase:
    PreparedStatement sql = Conn.prepareStatement("SELECT
    NAME FROM MY_TABLE");
    ResultSet results = sql.executeQuery();
    String Name = results.GetString("NAME");
    out.println(myName);
    I'm able to display the value of 'myName' (Tom), but
    if try:
    if (myName.equals("Tom")) {...}
    or
    if (myName == "Tom") {...}
    There is no response.
    Does anybody have any experience?
    Thank you.

  • SQLException after end of result set

    hi guys.
    im in a lot of bother at the moment.
    i have a GUI with a database in mysql. my gui is a recommender system and so users need to log in etc...
    i know for certain that the gui does connect to the database because when a new user enters there details it does get updated in the database.
    my problem is that when the user tries to gain acces to the system by going to the 'current user' and entering there details nothing happens.
    i am finding it very difficult to find out what the problem is, i have been trying for over a week but no luck and im hoping somebody will know how to help me.
    please could somebody help me here, i have a very short time aswell. monday.
    here is my code below.
    thank-you very much for your help
    its not normal to post the whole class here but im really really stumped.
    the errors that appears in the dos window is SQLException After end of result set.
    *     Function: This class is used for loggin in. It looks for the user name and password           *
    *          the user enters in the database. If there is no match an error message will appear     *
    *          to the user. If there is a match the system logs the user in and dispalys the chose      *
    *          topic page                                   *
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import com.mysql.jdbc.Driver;
    import java.sql.*;
    import java.awt.BorderLayout;
    import java.io.IOException;
    public class CurrentUserFrame extends JPanel implements ActionListener {
         // private is used so object variables cannot be changes by another class.
         private JButton loginButton = null ;
         private JTextField userName = null ;
         private JTextField password = null ;
         private JLabel userLabel = null ;
         private JLabel passwordLabel = null ;
         Boolean loginSuccess ;
         private JPanel cardPanel = null ;
         public CardLayout cardLayout = null ;
         protected static com.mysql.jdbc.Driver mysqlDriver = null;
         String passwordDbase ;
         String usernameDbase ;
              private CardLayout getCardLayout () {
              if (cardLayout == null ) {
              cardLayout = new CardLayout () ;
              return cardLayout ;
         private JPanel getCardPanel () {
         if (cardPanel == null) {
         cardPanel = new JPanel () ;
         return cardPanel ;
         // creates the background colours for the panels by specifying the amounts of red
         // green, blue where 0.5F is the least amount and 1.0F is the most
         Color currentTitleColor = new Color (0.58F, 0.73F, 0.83F) ;
         Color currentMainPanelColor = new Color (0.980F, 0.973F, 0.843F) ;
         public CurrentUserFrame ()
              setLayout (new BorderLayout ()) ;
              JPanel mainCPnl = new JPanel () ;
              mainCPnl.setLayout (new BorderLayout ()) ;
              JPanel mainPanel = new JPanel () ;
              // maindisplaypanel will be set with a borderlayout
              mainPanel.setLayout (new BorderLayout ());
              JPanel descriptionPanel = new JPanel ();
              descriptionPanel.setLayout(new BorderLayout ());
              // creates a textarea for the title and description
              JTextArea description2 = new JTextArea ("\t\tCurrent User Page\n\n" +
              "Please enter your user name and password to login.\n\n" +
              "If you have forgotten your user name or password click on " +
              " 'FORGOT PASSWORD'.") ;
              // stops the text area being edited by the user
              description2.setEditable (false) ;
              // once the text in description reaches the end of the textarea it will start a new line
              description2.setLineWrap (true) ;
              //sets the background colour of the textarea
              description2.setBackground (currentTitleColor) ;
              //sets the type of font with its size for the description textarea
              description2.setFont (new Font ("TimesRoman", Font.BOLD, 16)) ;
              // the descriptionpanel will be placed in the mainpanel at the top.
              mainPanel.add (descriptionPanel, BorderLayout.NORTH) ;
              descriptionPanel.add(description2, BorderLayout. NORTH) ;
              JPanel currentUserPanel = new JPanel () ;
              currentUserPanel.setLayout (new BoxLayout (currentUserPanel, BoxLayout.Y_AXIS)) ;
              // creates a button with an actionlistener so t can carryout a task when it is pressed.
              // the settooltiptext () method displays a message when the user hovers over the button with the curser
              loginButton = new JButton ("Log In") ;
              loginButton.addActionListener(this) ;
              loginButton.setToolTipText ("Logs you into the system") ;
              // creates a text field which is 25 characters in length for the user to enter their name
              userName = new JTextField (25) ;
              // creates a text field which is 15 characters in length for the user to enter their password
              password = new JPasswordField (15) ;
              userLabel = new JLabel ("User Name") ;
              passwordLabel = new JLabel ("Password") ;
              //adds the text fields and the JLabels to the currentuserPanel
              currentUserPanel.add (userLabel) ;
              currentUserPanel.add (userName) ;
              currentUserPanel.add (passwordLabel) ;
              currentUserPanel.add (password) ;
              currentUserPanel.add (loginButton) ;
              JPanel loginPanel = new JPanel () ;
              loginPanel.setLayout (new FlowLayout (FlowLayout.CENTER, 0, 170)) ;
              loginPanel.setBackground (currentMainPanelColor) ;
              loginPanel.add (currentUserPanel, BorderLayout.CENTER) ;
              mainPanel.add (loginPanel, BorderLayout.CENTER) ;
              JPanel chooseTopicCard = new JPanel () ;
              chooseTopicCard.setLayout (new GridLayout (0, 1, 0, 10)) ;
              ChooseTopic frame8 = new ChooseTopic () ;
              frame8.setVisible (true) ;
              chooseTopicCard.add(frame8) ;
              // this will create the panel for the maincontent area and sets the layout
              JPanel cp = getCardPanel();
              cp.setLayout(getCardLayout());
              cp.add("card3",mainPanel) ;
              cp.add("card7", chooseTopicCard) ;
              cardLayout.show (getCardPanel () , "card3") ;
              // this adds the cardlayout to the main panel and then adds the mainpanel screen
              mainCPnl.add(cp) ;
              this.add (mainCPnl) ;
         public void actionPerformed (ActionEvent event) {
              Object source = event.getSource () ;
              if (source == loginButton) {
                   // creates a string to connect to the local host and database
                   // the following 10 lines of code is from the mysql website
                   String url = "jdbc:mysql://:3306/project" ;
                   Connection con = null ;
                   // com.mysql.jdbc.Driver is a folder downloaded from mysql website
                   try {
                        mysqlDriver = (com.mysql.jdbc.Driver) Class.forName ("com.mysql.jdbc.Driver").newInstance () ;
                   } catch ( Exception E) {
                   throw new RuntimeException ("Can not load driver class com.mysql.jdbc.Driver") ;
                   try {
                   // attempts a connection with the computer     
                   // root is used as a default so i can have full access to the database
                   con = DriverManager.getConnection (url,"root","") ;
                   // trys to log in to the database
                   // statement is a mysql class
                   Statement select = con.createStatement ();
                   ResultSet result = select.executeQuery ("select * from user_login") ;                    
                   String userNameText = userName.getText();
                   String passwordText = password.getText();
                   if (userNameText.equals("") || passwordText.equals("")) {
                        JOptionPane okoptionpane = new JOptionPane () ;
                        okoptionpane.showMessageDialog(null, "You have entered your username or password incorrectly, please try again") ;
                        while ((result.next()) && (result != null))
                             //String usernameval ;
                             //String passwordval ;
                             passwordDbase = result.getString("password");
                             usernameDbase = result.getString("user_name");
                             //passwordDbase = "password";
                             //usernameDbase = "user_name";
                             if ((passwordDbase.equals(passwordText)) && (usernameDbase.equals(userNameText))) {
                             cardLayout.show(getCardPanel(), "Card7");                         
                        catch (Exception e) {
                        e.printStackTrace() ;
                        finally {
                        if (con != null ) {               
                             try {con.close () ;  }
                             catch (Exception e) {
                             e.printStackTrace () ;
    LIZ

    ooppps, very sorry, you can guess im new to this forum. sorry again. i thought maybe the whole code was needed.
    i have posted all the output from the dos window.
    java.sql.SQLException: After end of result set
    at com.mysql.jdbc.ResultSet.checkRowPos(ResultSet.java:3628)
    at com.mysql.jdbc.ResultSet.getString(ResultSet.java:1763)
    at com.mysql.jdbc.ResultSet.getString(ResultSet.java:1827)
    " at CurrentUserFrame.actionPerformed(CurrentUserFrame.java:214) "
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Unknow
    n Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Sour
    ce)
    at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    i think it is mainly line that is in speach marks. line 214.
    the error that comes up says." after end of result set "
    thank-you
    and sorry once again, im in a bit of a panic,
    Liz

  • Result Set problem!!!Plz urgent

    Hi,
    I am using jsp page with database connection.In jsp page i have two button called move next and move previous.
    In database 2 records are there.If i open the jsp page first record will be displayed.If i click next record it showing 2nd record.If i click previous record it showing 1st record.Once again if i click next record it is showing that record not found...........What may be the problem????.
    Note:For each time button click i will pass the result set object in session variable.Whether it is a correct one..
    Plzz help me ya...........

    this is for move next:::
    ResultSet result=null;
    Connection connection=null;
    String candyid="";
    result = (ResultSet)session.getAttribute("resget");
    result.next();
    if(!result.next())
    %>
    <Script>
    alert("Record Not Found");
    </Script>
    <%
    result.previous();
    candyid=result.getString(1);
    session.setAttribute("resget",result);
    %>
    <input type=hidden name="hide" value="yes">
    <input type=hidden name="nextid" value=<%= candyid %>>
    <Script>
    document.AddCandetails2.action="modifyCandidate1.jsp";
    document.AddCandetails2.submit();
    </Script>
    <%
    else
    candyid=result.getString(1);
    System.out.println("candi next id"+candyid);
    session.setAttribute("prevresget1",result);
    System.out.println("resultset for set attar in next"+result);
    %>
    <input type=hidden name="hide" value="yes">
    <input type=hidden name="nextid" value=<%= candyid %>>
    <Script>
    document.AddCandetails2.action="modifyCandidate1.jsp";
    document.AddCandetails2.submit();
    </Script>
    <%
    this is for move previous:::
    ResultSet result=null;
    Connection connection=null;
    String candyid="";
    if(session.getAttribute("prevresget1")==null)
    result = (ResultSet)session.getAttribute("resget");
    else
    result = (ResultSet)session.getAttribute("prevresget1");
    if(!result.previous())
    %>
    <Script>
    alert("Record Not Found");
    </Script>
    <%
    result.next();
    candyid=result.getString(1);
    session.setAttribute("resget",result);
    %>
    <input type=hidden name="hide" value="yes">
    <input type=hidden name="nextid" value=<%= candyid %>>
    <Script>
    document.AddCandetails2.action="modifyCandidate1.jsp";
    document.AddCandetails2.submit();
    </Script>
    <%
    else
    candyid=result.getString(1);
    session.setAttribute("prevresget1",result);
    %>
    <input type=hidden name="hide" value="yes">
    <input type=hidden name="nextid" value=<%= candyid %>>
    <Script>
    document.AddCandetails2.action="modifyCandidate1.jsp";
    document.AddCandetails2.submit();
    </Script>
    <%
    this is the code............... can u give me the solution

  • PreparedStatement only returning 256 results

    Hi!
    I'm working on a project where the user can enter up to 1000 ids to fetch the corresponding objects from our Oracle database, connected using the 11.1.0.7.0 jdbc drivers. However, only 256 rows were available in the result. So I made a simple test, like so:
    public static void main(String[] args) throws Exception {         Class.forName("oracle.jdbc.OracleDriver");         Connection connection = DriverManager.getConnection("jdbc:oracle:thin:myuser/mypassword@myurl:1521:mydb");     PreparedStatement select = connection.prepareStatement("SELECT id FROM t01abc_regenh WHERE id in (?, ?,..., ?)"); // 1000 ?s         String[] idArray = new String[] {"010000010", "010000026", ..., "010000981"}; // 1000 ids         for(int i = 0; i<idArray.length; i++) {       select.setString(i+1, idArray);
    ResultSet result = select.executeQuery();
    boolean hasNext = result.next();
    for(int i = 1; hasNext; i++) {
    System.out.println(i + " : " + result.getString(1));
    hasNext = result.next();
    result.close();
    select.close();
    connection.close();
    The database logs show that the query is using the 1000 ids, but only the first 256 results were printed. So I tried again, using a non-prepared statement:
    public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.OracleDriver");
    Connection connection = DriverManager.getConnection("jdbc:oracle:thin:myuser/mypassword@myurl:1521:mydb");
    Statement select = connection.createStatement();
    String[] idArray = new String[] {"010000010", "010000026", ..., "010000981"}; // 1000 ids
    StringBuilder query = new StringBuilder("SELECT id FROM t01abc_regenh WHERE id in (");
    for(int i = 0; i<idArray.length; i++) {
    query.append('\'').append(idArray[i]).append("', ");
    query.delete(query.length() - 2, query.length());
    query.append(')');
    ResultSet result = select.executeQuery(query.toString());
    boolean hasNext = result.next();
    for(int i = 1; hasNext; i++) {
    System.out.println(i + " : " + result.getString(1));
    hasNext = result.next();
    result.close();
    select.close();
    connection.close();
    This time the full 1000 results where printed. Is this a general thing with prepared statements or is it an issue with the Oracle database or the jdbc drivers? Is there a way to increase the number of returned results? Please help!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    >
    Is this a general thing with prepared statements or is it an issue with the Oracle database or the jdbc drivers?
    >
    None of the above - it is an issue with your code. You are comparing apples to oranges; an invalid comparison.
    The queries are not identical so you should not expect identical results.
    You are using this data
        String[] idArray = new String[] {"010000010", "010000026", ..., "010000981"}; // 1000 idsin two different queries.
    The first test constructs a query of the form
        "SELECT id FROM t01abc_regenh WHERE id in (010000010, 010000026,..., ?)"); // 1000 ?sAnd the second constructs a query of the form
        "SELECT id FROM t01abc_regenh WHERE id in ('010000010', '010000026',..., ?)"); // 1000 ?sThat is the first query uses numeric values for the IN clause and the second query uses string values.
    If the actual data is VARCHAR2 these will not match the same values.
    A string value of '010000010' will not match a numeric value of 010000010 because when 010000010 is converted back to a string for the comparison there will be no leading zeroes so the converted value will be '10000010'
    So the first query tries to match '010000010' with '10000010' and they do not match.

  • Queries that return no results cause exception

    When I run a query that returns no records, my program crashes and burns, giving me the error message that no data was found; something doesn't seem right about that. Shouldn't it be able to handle this situation? Does anyone know what I'm doing wrong? Thanks.

    I'd rewrite your snippet this way:
    // Here's where you get your data
    String sql = "SELECT FiscalYear FROM Requests WHERE Agency = ?";                          
    stmt = con.prepareStatement(sql);                     
    stmt.setString(1, agency);
    ResultSet result = stmt.executeQuery();                                                   
    List fiscalYears = new ArrayList();
    while (result.next())
        fiscalYears.add(result.getString("FiscalYear"));
    result.close();
    stmt.close();
    // Here's where you do something with it.
    int numFiscalYears = fiscalYears.size();
    if (numFiscalYears > 0)
        for (int i = 0; i < numFiscalYears; ++i)
            if (i == 0)
                //if data was returned, get first row   
                //put FY value into echoPacket and send to client  
                echoPacket = DGramIt.toDatagram((String)fiscalYears.get(i), packet.getAddress(), packet.getPort());
                socket.send(echoPacket);                                                                  
            else
                //for each row of data    
                socket.receive(dummyPacket);//receive dummy packet         
                //put FY value into echoPacket and send to client      
                echoPacket = DGramIt.toDatagram((String)fiscalYears.get(i), packet.getAddress(), packet.getPort());    
                socket.send(echoPacket);   
    else
        //if no data, send client message  
        //put message into echoPacket and send to client   
        echoPacket = DGramIt.toDatagram("no data", packet.getAddress(), packet.getPort());   
        socket.send(echoPacket);
    }Separate out getting the results from what you do with them. - MOD

  • Insert web services result into textbox in JSP

    Basically, I had using HTML to create a textbox in the earlier:
    <input id="Destination" style="z-index: 140; left: 413px; position: absolute; top: 238px"
    type="text" disabled="disabled" name="Destination" />
    Then now I had using JSP to consume the web services:
    <%-- start web service invocation --%><hr/>
    <%
    try {
    if(request.getParameter("btn")!=null)
         org.tempuri.CheckTravelBooking service = new org.tempuri.CheckTravelBooking();
         org.tempuri.CheckTravelBookingSoap port = service.getCheckTravelBookingSoap();
    java.lang.String bookingID = request.getParameter("ID");
    // out.println("Result=" +bookingID);
         // TODO process result here
         org.tempuri.ArrayOfString result = port.checkBooking(bookingID);
    // out.println("Result="+bookingID);
    // for(int i=0; i<result.getString().size(); i++)
    {%>
    <table>
    <tr>
    <td> <%=result.getString().get(0)%></td>
    <td> <%=result.getString().get(1)%></td>
    <td> <%=result.getString().get(2)%></td>
    <td> <%=result.getString().get(3)%></td>
    <td> <%=result.getString().get(4)%></td>
    <td> <%=result.getString().get(5)%></td>
    <td> <%=result.getString().get(6)%></td>
    <td> <%=result.getString().get(7)%></td>
    <td> <%=result.getString().get(8)%></td>
    <td> <%=result.getString().get(9)%></td>
    <td> <%=result.getString().get(10)%></td>
    </tr>
    </table>
    <%
    } catch (Exception ex) {
         // TODO handle custom exceptions here
    out.println(ex.getMessage());
    %>
    <%-- end web service invocation --%><hr/>
    How should I insert my result in the web services to my textbox that had been designed in the earlier???

    If you separate the code into
    JSP - reserve only for HTML and front end logic
    Servlet - to communicate between JSP and Business Layer/Database Layer
    Business layer - to communicate with database layer
    the code will be more manageable, than putting all code in just one JSP file.
    The above structure is called Model-View-Controller MVC , if you study that what you are trying to do will be much easier.

  • RMI to servet to Access DB not returning any results in Vector

    We have a servlet (on the TomCat 3.2.3 web server) that receives parameters from an RMI Server program. The connection is done through the use of the HttpUrlconnection. The doGet() of the HttpServlet reads the parameters and assigns them to a data object of type thisData (which consists essentially of private data members of type: Strings and integer and double variables). The objects are then assigned to a vector, which is then sent back from servlet via getOutputStream(). We get no compilation errors nor do we get any errors during runtime. The connection to the database (MS Access) seems ok as it works with just the client, excluding the RMI. There is no response at the client side when we do a query - no results are returned in the Vector (message says it is 'empty'). What could possibly be wrong? Is there any particular aspect that we should look at? Any immediate help would be greatly appreciated. Thank you. The code from the servlet is below. Please let us know if this is correct. Thank you.
    Flag =request.getParameter("Flag");
    int flag =Integer.parseInt(Flag);
    if (Flag == 1) {  // SELECT to get data to display in GUI
    departdate=request.getParameter("depdate");
    departcity=request.getParameter("depcity");
    destincity=request.getParameter("destincity");
    try{
    sqlQuery.setString( 1, departdate );
    sqlQuery.setString( 2, departcity );
    sqlQuery.setString( 3, destincity );
    }catch(SQLException except){ }
    try {
    ResultSet results = sqlQuery.executeQuery();
    catch (SQLException myexcpt) {
    JOptionPane message here }
    try{
    ResultSetMetaData queryMetaData = results.getMetaData();
    if ( noOfRecords >0 ) {
    ObjectOutputStream outtoRMI = new ObjectOutputStream
    (response.getOutputStream() );
    results.beforeFirst();
    thisData anObject = new thisData();
    Vector theRecords = new Vector();
    while ( results.next() )
    // get value from ResultSet, then 'set' to an attribute
    anObject.setClientNo( results.getInt(1) );
    anObject.setAirline( results.getString(2) );
    anObject.setdepartCity( results.getString(3) );
    anObject.setdepDate(results.getString(4) );
    anObject.setdepTime( results.getInt(5) );
    anObject.setdestnCity(results.getString(6) );
    anObject.setPrice( results.getDouble(7) );
    anObject.setFlightNum( results.getInt(8) );
    theRecords.addElement( anObject );
    outtoRMI.writeObject( theRecords ); // write vector
    outtoRMI.close(); // close writer
    } // end of if
    results.close(); // close resultSet
    sqlQuery.close(); // close query
    catch(SQLException nextExcept){ }
    } // end of if stmt

    Sorry, variable noOfRecords is set by result of getRow(). (When editing to display this, I inadverdently missed/deleted :)
    Specifically wondering if use of ObjectOutputStream (response.getOutputStream) is appropriate.
    In other words if a vector of complex objects (attributes of int, String, and double) can be sent back to RMI server via this mechanism. I have heard that only an object at a time (not a whole vector of them) can be transmitted. Is this true???
    Relevant (corrected) code follows:
    ResultSetMetaData queryMetaData = results.getMetaData();
    results.last();
    int noOfRecords = results.getRow();
    if ( noOfRecords >0 ) {
    if ( noOfRecords >0 ) {
    ObjectOutputStream outtoRMI = new ObjectOutputStream
    (response.getOutputStream() );
    results.beforeFirst();
    thisData anObject = new thisData();
    Vector theRecords = new Vector();
    while ( results.next() )
    // get value from ResultSet, then use 'set' methods to set an attribute
    anObject.setClientNo( results.getInt(1) );
    //etc.
    theRecords.addElement( anObject );
    outtoRMI.writeObject( theRecords ); // write vector
    outtoRMI.close(); // close writer
    } // end of if

  • Fetching query result for editbox

    Hello to everyone. I just started developing Windows application (after 2 years pause). So, I'm working 'with' MFC Dialog based app.
    I want to fill combo box (or edit box it doesn't matter) with MySQL query result. I have these codes:
    void CConnectToMySQLDlg::OnWriteToDatabase()
    CString get, set;
    m_edit.GetWindowText(get);
    CT2CA temp_string(get);
    string s_get(temp_string);
    if (m_edit.GetWindowTextLength() != 0) // if you can please write this line better.
    MySQL_Driver *driver;
    Connection *dbConn;
    Statement *statement;
    ResultSet *result;
    driver = get_mysql_driver_instance();
    dbConn = driver->connect("tcp://127.0.0.1:3306", "root", "connection");
    dbConn->setSchema("world");
    statement = dbConn->createStatement();
    result = statement->executeQuery(s_get);
    //CStringArray comboArray;
    /*comboArray.Add(_T("bir"));
    comboArray.Add(_T("iki"));
    comboArray.Add(_T("uc"));
    comboArray.Add(_T("dord"));
    comboArray.Add(_T("bes"));
    comboArray.Add(_T("ffsfsfs"));
    comboArray.Add(_T("bfsfsfsdes"));
    comboArray.Add(_T("bczxczxes"));
    comboArray.Add(_T("aadafdsbes"));
    comboArray.Add(_T("zczxawfebes"));*/
    //comboMysql.ResetContent();
    string s_set = "string";
    set.Format(_T("%S"), s_set.c_str());
    while (result->next())
    // here how can I set edit box value?
    // So, how can I convert
    AfxMessageBox(L"dsadasd");
    delete result;
    delete statement;
    delete dbConn;
    else // handling user input
    AfxMessageBox(L"not allowed");
    I can get input stream and successfully(1) execute it but I don't know how to set its result(s).
    (1) --- In this case I entered this SQL line:
    select ID, Name from city where ID = 1 or ID = 2 or ID = 3 or ID = 4
    and it alerted me 4 times.
    p.s. If there any problematic codes please tell me the correct variant(s).
    Best regards,
    Mirjalal.

    I solved my problem. I pasted working codes below.
    void CmysqlDlg::OnBnClickedButton1()
    CString get, set, ComboString;
    edit.GetWindowText(get);
    CT2CA temp_string(get);
    std::string s_get(temp_string);
    if (edit.GetWindowTextLength() != 0) // if you can please write this line better.
    MySQL_Driver *driver;
    Connection *dbConn;
    Statement *statement;
    ResultSet *result;
    driver = get_mysql_driver_instance();
    dbConn = driver->connect("tcp://127.0.0.1:3306", "root", "connection");
    dbConn->setSchema("world");
    statement = dbConn->createStatement();
    result = statement->executeQuery(s_get); // executes the user "input"
    comboBox.ResetContent();
    // ofstream y("text.txt"); // actually i don't need this anymore :P
    while (result->next())
    string name_string = result->getString("Name"); // Name is the my tbl column name
    CString cs_name_string(name_string.c_str());
    comboBox.AddString(cs_name_string);
    delete result;
    delete[] result;
    delete statement;
    delete[] statement;
    delete dbConn;
    delete[] dbConn;
    else // handling user input
    AfxMessageBox(L"olmaz");
    Thanks.
    Mirjalal

  • MsSQL 2000+Resultset.getString()

    Guys,
    I really need help for this issue. Here is the problem:
    - I am using Java 1.3.1/SE + EE
    - I have Ms SQL/2000
    This is the java code:
    Connection conn = null;
    String name;
    try
         conn = connectionPool.getConnection();
    Statement statement = conn.createStatement();
    ResultSet results = statement.executeQuery
    ("select * from USERAUTHENTICATION");
    while (results.next())
    name = results.getString("UserID");
    statement.close();
    finally
    if (conn != null)
    When java runs results.getString("UserID"), it gives this error:
    java.sql.SQLException: [Microsoft][ODBC SQL Server Driver]Invalid Descriptor Index
    It is weird because this code works under Oracle database.
    I will appreciate any help.
    PS. I am not expert a Java programmer. So if you have an answer, please give a little bit detail.
    Thank you
    Murat

    Thanks for the answer. I am sure that the column name and my text are exactly the same. The column is VARCHAR.
    Let me give more info:
    - One thing I noticed is that Resultset.getDate() works properly.
    - Resultset.getString() does not work for none of varchar type in SQL.
    I make the connection that way:
    try
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    } catch (Exception ignore) {}
    connectionPool = new MyConnectionPool(
    "jdbc:odbc:MYDATABASENAME", "sa", "");
    I am just wondering weather jdbc.odbc works properly or not.
    Thank you
    Murat

  • ResultSet + getString("field")

    hey all!
    just a question. i ve been trying to do stuff with ResultSets. basically i ve got mysql connected and everything is fine except one little thing. when i get my ResultSet and then try to get the fields from it
    eg
    ResultSet result = selects.getResultSet(); /// this gives me my result set
    while(result.next()){
    String email = result.getString("email");
    String mess = result.getString("message");
    String date = result.getString("date");
    System.out.println(email + " xx " + mess + " xx " + date);
    now the problem. lets say i ve got 3 records (lines) in that resultSet. but this way only the last two show???? the first one never shows. to fix it i have to do this
    ResultSet result = selects.getResultSet(); /// this gives me my result set
    String e = result.getString("email");
    String m = result.getString("message");
    String d = result.getString("date");
    System.out.println(e + " xx " + m + " xx " + d); // this gives me my first record
    while(result.next()){ // this gives me my other two (second and third) records
    String email = result.getString("email");
    String mess = result.getString("message");
    String date = result.getString("date");
    System.out.println(email + " xx " + mess + " xx " + date);
    it is not a big issue and i its quite late so instead of doing research on google im going to sleep and hpefully tomorrow someone will reply ((:
    thanks
    v.v.
    os = slackware 11.0
    java =
    java version "1.5.0_09"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_09-b01)
    Java HotSpot(TM) Client VM (build 1.5.0_09-b01, mixed mode, sharing)

    This is the code I'm using right now and it's working
    if (conn != null)  {
                  mySqlDB.setSql("SELECT * FROM apps ");
                  stmt = conn.prepareStatement(mySqlDB.getSql());
                  results = stmt.executeQuery();
             while(results.next()){
                  String name = results.getString("name");
                  int id = results.getInt("id");
                  String email = results.getString("Email");
                  Application temp = new Application(name, id,  email);
                  applicationList.add(temp);
             }

  • Can not get PK-FK in meta-Data of MySql....Help me pls.

    Hello Every one.
    I can not to get the PK and FK from Meta-Data Database of mysql-4.1.1a-alpha. Anyway I tried to do the
    followihg
    1. OS windows 2000 Pro.
    2. set configuration Script support InnoDB Table Type as the follow in my.ini file.
    [mysqld-nt]
    innodb_data_home_dir = C:\mysql\data
    innodb_data_file_path =\ibdata\ibdata1:2000M // in folder \data\ i was created folder ibdata
    3. I try to create data as reference in example java code and table :persons , shirt as the example in
    Create innodb table Type of mysql doc.
    4. the code test as following
    In the test code i can get the result only from method : getPrimarykey(...); only and the other method ,getExportedKeys, getImportedKey , getCrossReference the result in ResultSet is null.
    anyway, this code i can apply in the oracle db with change db driver .
    I wish the answer why? and the actually the second parameter of this parameter , as refer scheme name , the scheme name is ?
    Thank you
    import java.sql.*;
    public class testMeta {
    public testMeta() {
    ResultSet rs=null;
    String url = "jdbc:mysql://localhost:3306/testinnodb";
    Connection con = null;
    try{
    Class.forName("org.gjt.mm.mysql.Driver");
    }catch(ClassNotFoundException ex){
    System.out.println(ex.getMessage());
    try{
    con = DriverManager.getConnection(url,"root","rootpwd");
    prtS("getConnection complete");
    DatabaseMetaData metaData = con.getMetaData();
    Connection con2 = metaData.getConnection();
    String type[] = new String[1];
    type[0] = new String();
    prtS("*************** GET Schemas ***************");
    rs = metaData.getSchemas();
                   while(rs.next()){
    System.out.println("12345");
    prtS("TABLE_CAT" + " : " + rs.getString(0));
    prtS("TABLE_CAT" + " : " + rs.getString("TABLE_SCHEM "));
                   rs=null;
    prtS("*************** GET PRIMARY KEYS ***************");
    rs = metaData.getPrimaryKeys(con.getCatalog(),null,"persons");
    while(rs.next()){
    prtS("TABLE_CAT" + " : " + rs.getString("TABLE_CAT"));
    prtS("TABLE_SCHEM" + " : " + rs.getString("TABLE_SCHEM"));
    prtS("TABLE_NAME" + " : " + rs.getString("TABLE_NAME"));
    prtS("COLUMN_NAME" + " : " + rs.getString("COLUMN_NAME"));
    prtS("KEY_SEQ" + " : " + rs.getString("KEY_SEQ"));
    prtS("PK_NAME" + " : " + rs.getString("PK_NAME"));
                   rs=null;
    prtS("*************** GET Exported KEYS ***************");
    rs = metaData.getExportedKeys(con.getCatalog(),null,"shirt");
    while(rs.next()){
    prtS("FKCOLUMN_NAME" + " : " + rs.getString("FKCOLUMN_NAME"));
                   rs=null;
    prtS("*************** GET Imported KEYS ***************");
    rs = metaData.getImportedKeys(con.getCatalog(),null,"persons");
    while(rs.next()){
    prtS("PKTABLE_CAT" + " : " + rs.getString("PKTABLE_CAT"));
    rs=null;
    prtS("*************** GET CrossReference ***************");
    rs = metaData.getCrossReference(con.getCatalog(),null,"persons",con.getCatalog(),null,"shirts");
    while(rs.next()){
    prtS("PKTABLE_CAT" + " : " + rs.getString("PKTABLE_CAT"));
    }catch(SQLException ex){
    prtS(ex.getMessage());

    How i know the jdbc driver not compatible to this
    mechanismBy reading the documentation tthat comes with your driver. Recent versions of the MySQL JDBC driver do support the getExportedKeys/ImportegKeys methods but the table needs to be crated as InnoDB.
    So run the SQL command
    show table statusWhats under the Type column for your table? If it isn't InnoDB then this isn't going to work.
    If it is InnoDB but getExportedKeys/ImportegKeys still don't work then you haven't used the "foreign key" constraint in your "create table" command

  • How to get details of a particular column in database.

    Hi dear friends,
    I am getting error while i try to get index information on a particular column.
    here is the code.. why it gives me error
    import java.sql.*;
    import java.util.StringTokenizer;
    public class TestIndex {
      final static String jdbcURL = "jdbc:timesten:client:CATSREPLICATION";
      final static String jdbcDriver = "com.timesten.jdbc.TimesTenClientDriver";
      final static String scheme = "CATSPROD";
      public static void main(java.lang.String[] args) {
        System.out.println("--- Database Viewer ---");
        try {
          Class.forName(jdbcDriver);
          Connection con = DriverManager.getConnection(jdbcURL, "", "");
          DatabaseMetaData dbmd = con.getMetaData();
          System.out.println("Driver Name: " + dbmd.getDriverName());
          System.out.println("Database Product: " + dbmd.getDatabaseProductName());
            // Get a list of all the indexes for this table
          // this MYSCHEME.TABLENAME has a composite unique key on 2 columns of it.
           * create table MYSCHEME.TABLENAME (id integer not null, name varchar(25) not null);
           * create unique key on MYSCHEME.TABLENAME(id,name);
            ResultSet indexList = dbmd.getIndexInfo(null,null,"MYSCHEME.TABLENAME",true,false);
            ResultSet columns = null;
            indexList.next();
            while(indexList.next()) {
              System.out.println(" Index Name: "+indexList.getString("INDEX_NAME"));
              String column = indexList.getString("COLUMN_NAME");
              System.out.println(" Column Name:"+column);
              columns =  dbmd.getColumns(null,"MYSCHEME","TABLENAME",column);
              System.out.println("---------------------------");
              System.out.println(columns.getString("IS_NULLABLE"));
              System.out.println("---------------------------");
            indexList.close();
          con.close();
        catch (ClassNotFoundException e) {
          System.out.println("Unable to load database driver class");
        catch (SQLException e) {
          System.out.println("SQL Exception: " + e.getMessage());
    it give error
    SQL Exception: Invalid cursor state
    why?
    thanks a lot
    Veena
    [ November 10, 2005: Message edited by: Veena Gupta ]

    indexList.next();
    while(indexList.next()) {You will be missing the first record due to this.
    columns =
    dbmd.getColumns(null,"MYSCHEME","TABLENAME",column);
    System.out.println("---------------------------");
    System.out.println(columns.getString("IS_NULLABLE"));You need to call columns.next() before using the getString(). If next() is not called, the cursor of the ResultSet is positioned before the first record and an attempting to read a record before positioning the cursor to the first record would result in an exception due to invalid cursor state.

  • Session tracking

    Hi there,
    I have a strange problem you may be able to shed some light on. At least I hope so. I'm working with an existing project using JSP's and Servlets and a backend MySQL database. The project entails the ability to perform ad hoc queries to the database. The source code files can be found at the bottom of the page at:
    http://www.eas.asu.edu/~cse494db/IonJDBC/JDBCExample.html
    The project contains one servlet called Contol.java and a bean called QueryBean.java. The Control servlet is first invoked using a POST call. In doing so, a Session object is created and an instance of QueryBean is created and stored in the Session object. The QueryBean contains the meta data for the database. A jsp called QueryInput.jsp loads and at the same time also activates a second browser window loading MetaTables.jsp. When MetaTables.jsp loads in the second window it calls
    QueryBean qb = (QueryBean)session.getAttribute("qBean");
    from the session object retrieving the QueryBean instance and the meta data is used to be displayed in a table. The first time this process occurs everything is fine, until I dismiss the window containing MetaTables.jsp.
    Here's what happens...QueryInput.jsp has a button on it. It is used to re-display the window that MetaTables.jsp loads into if the user dismisses that window when it first loads. Here's where the interesting part comes in. If I click on the button in the main browser window containing QueryInput.jsp the second browser window appears alright, but for whatever reason all the data that was in the QueryBean instance is gone. MetaTables.jsp loads and attempts to obtain the QueryBean instance again from the Session object, but there is no data to display. It's gone!
    What's going on? Does anybody know?
    Alan
    ***************QueryInput.jsp*************************
    <%@ page import = "java.io.*" %>
    <%@ page import = "java.sql.*" %>
    <%@ page import = "com.components.QueryBean" %>
    <jsp:useBean id="qBean" class="com.components.QueryBean" scope="session"/>
    <%
    String ManagerOnBoard = (String)session.getAttribute("ManagerOnBoard");
    if(ManagerOnBoard == null)
    %>
    <HTML>
    <HEAD>
    <TITLE>MainMenu</TITLE>
    <link href="site.css" rel="stylesheet" type="text/css">
    </HEAD>
    <body>
    <h1>ACCESS DENIED</h1>
    </body>
    </html>
    <%
    else
    %>
    <HTML>
    <head>
    <link href="site.css" rel="stylesheet" type="text/css">
    <script language=javascript>
        function MetaData()
    window.open('MetaData.jsp','','toolbar=no,resizable=yes,menubar=no,location=no,height=400,width=400');
    </script>
    </head>
    <BODY onLoad="MetaData()">
    <b><center><h2><jsp:getProperty name="qBean" property="dbName"/> Database </h2></center></b>
    <hr>
    <form action=MainMenu.jsp target =_parent>
    <p><input type="SUBMIT" VALUE="Return to Main Menu"></p>
    </form>
    <b>SQL Select/Insert/Update/Delete:</b><br>
    <table><tr><td>
    <form name="MyForm" action="/scholastic/Control" method="GET" TARGET="Output" onsubmit="return checkForm(this)">
      <p><textarea name="query" rows=9 cols=40>
      </textarea></p>
      </td><td><p><input type="SUBMIT" VALUE="Submit">��
      </p><p><input type="RESET" name="clear" VALUE="Clear">��
      </p><p><input type="button" value="Open MetaData" onClick="MetaData()">
    </form>
    </td>
    </tr>
    </table>
    </BODY>
    </HTML>
    <%
    %> **********************MetaTables.jsp*****************
    <%@ page import = "java.io.*" %>
    <%@ page import = "java.sql.*" %>
    <%@ page import = "java.util.*" %>
    <%@ page import = "com.components.QueryBean" %>
    <!--jsp:useBean id="qBean" class="com.components.QueryBean" scope="session"/-->
    <%
       QueryBean qb = (QueryBean)session.getAttribute("qBean");
       Vector tables = (Vector)qb.getTables();
       String ManagerOnBoard = (String)session.getAttribute("ManagerOnBoard");
    if(ManagerOnBoard == null)
    %>
    <HTML>
    <HEAD>
    <TITLE>MainMenu</TITLE>
    <link href="site.css" rel="stylesheet" type="text/css">
    </HEAD>
    <body>
    <h1>ACCESS DENIED</h1>
    </body>
    </html>
    <%
    else
    %>
    <HTML>
    <head>
    <link href="site.css" rel="stylesheet" type="text/css">
    </head>
    <body>
    <!--jsp:getProperty name="qBean" property="dbName"/-->
    <center><h2> <%=qb.getDbName()%> Database MetaData</h2></center>
    <%
       for(int i =0; i< tables.size(); i++)
    %>    <table><tr>
          <%
          StringTokenizer token = new StringTokenizer((String)tables.get(i));
          String tableName = ((String)token.nextToken()).toUpperCase();
          %>
          <th><a href="/scholastic/Control?tableName=<%=tableName%>" target=Output><%=tableName%></a></th><th> :</th>
          <%
          while(token.hasMoreTokens())
         %>  
               <th><%=token.nextToken()%></th>
         <%
         %>
          </tr></table>
    </body>
    </html>
    <%
    %> ******************Control.java************************
    package com.components;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import javax.sql.*;
    import javax.naming.*;
    public class Control extends HttpServlet
        Connection connection = null;   // the connection to the database
        Statement statement = null;   // a statement object for the queries
        String dbName;           // the database name
        public QueryBean qBean = null;
        private ServletContext context;   // objects used to transfer control to the jsp pages
        /*Initializing the servlet*/
        public void init(ServletConfig config) throws ServletException
            super.init(config);
    context = config.getServletContext(); 
         The doPost method handles POST requests
         This method is accessed first in from the time the user will
         enter a datasource name in the main page.
         The function will first establish a connection to the database
         with the requested data source name. If the data
         source does not exist then the control is tranferred to an error page
         with a corresponding message. If the database exists
         then we save time by getting all the meta-data from the database
         ( table names, and columns) and storing them in the
         bean. The bean is stored in the session object and control is
         transferred to the query page which loads the two frames. One
         for entering the query and one for results. This function is
         accessed only whenever we are in the main page.
        public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException
          ResultSet rsTables = null; //ResultSet objects for the database tables and columns
          ResultSet rsColumns = null;
          //databse metadata object to access the meta-data from the database   
          DatabaseMetaData dbmd = null;
          qBean = new QueryBean(); // the bean object to store the information
          //the database source name entered from the user
          dbName = "scholastic_db";
          //store the database name in the query bean so pages can diplayed it later.
          qBean.setDbName(dbName);  
          String tableName;
          // The code below gets the database table names and
          // columns and stores them in the bean
          try
             Context ctx = new InitialContext();
             if(ctx == null )
                throw new Exception("No Context available...");
             DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/Scholastic");
             if (ds != null)
               connection = ds.getConnection();
               if(connection != null)
                 HttpSession session = req.getSession(true);
                 dbmd = connection.getMetaData();
                 rsTables = dbmd.getTables(null, null, null, null);
          while (rsTables.next())
            StringBuffer buff = new StringBuffer();
                   tableName = rsTables.getString("TABLE_NAME");
            if (rsTables.getString("TABLE_TYPE").equals("TABLE"))
                     buff.append(tableName + " ");
              rsColumns = dbmd.getColumns(null,null,tableName,null);
                     while (rsColumns.next())
                        buff.append(rsColumns.getString("COLUMN_NAME") + " ");
              qBean.setTables(buff.toString());
                // put the bean in the session
                session.setAttribute("qBean", qBean); 
                // transfer control to the query page
                res.sendRedirect("/scholastic/manager/Query.jsp");
                rsTables.close();
                rsTables = null;
                rsColumns.close();
                rsColumns = null;
                connection.close();
                connection = null;
          catch (Exception e)
            // If there is an error with the database source
            // transfer control to an error page
            try
              connection.close();
              connection = null;
            catch(SQLException sqle){;}
    res.sendRedirect("/scholastic/manager/errorDbSource.jsp");
          finally
            // Always make sure result sets and statements are closed,
            // and the connection is returned to the pool
            if (rsTables != null)
              try { rsTables.close(); } catch (SQLException e) { ; }
              rsTables = null;
            if (rsColumns != null)
              try { rsColumns.close(); } catch (SQLException e) { ; }
              rsColumns = null;
            if (connection != null)
              try { connection.close(); } catch (SQLException e) { ; }
              connection = null;
       /* The doGet method handles GET requests. This function is accessed
          every time we enter a query using the query form of
          the queryInput pages and also every time we want to display
          the contents of a table in the metadata window since we
          actually perform a SELECT * FROM tableName statement. We
          display the results in the same page if there are select statements
          to save code. There is only one difference. In the query frames,
          we actually display the query itself along with the results,
          but in the metadata we dont. Since we access only one method, the doGet
          for both operations we determine at the beginning of
          the function; if we came from queryInput or from metaTables page.
          If we came from the queryInput page we perform the necessary
          calculation and we put the results along with the query itself
          in a bean. If it is a select statement we transfer control to the
          QueryOutputProccess page where we display the query itself and a
          table with the results. If its an update, insert, or delete,
          we perform the operation but we transfer control in a different
          page; the QueryOutputProccesUpdate where we output the result of
          our statement.
          If we come from the metadata, then we perform the query SELECT * FROM
          tableName and we store the results in the bean as we did
          before. Since we don't display the query itself from the metadata but
          we are using the same page we save to the query bean an
          empty string.
          In all the cases, we check if the user has made an error by entering
          no data or bad data in the query window. If this is the case,
          we transfer control to a page where we display the appropriate message.
          If the user has caused an SQL exception like selecting data from a table
          that does not exist, we get the corresponding message
          of the exception and we transfer control to another page.
       public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException
          //System.out.println("Entering doGet");
          String query; // the query
          ResultSet resultSet = null; // a resultset object that holds the results of the query
          QueryBean qBean = new QueryBean();   // a QueryBean object
          try
            Context ctx = new InitialContext();
            if(ctx == null )
               throw new Exception("No Context available...");
            DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/Scholastic");
            if (ds != null)
               connection = ds.getConnection();
               if(connection != null)
                 HttpSession  session = req.getSession(true); //get the session object
                 statement = connection.createStatement(); // create a statement object
                 // check to see if the user is coming from the metadata 
                 String tableName = (String)req.getParameter("tableName");
                  NOTE: THE LINUX OPERATING SYSTEM IS PARTICULAR ABOUT CASE
                  SENSITIVITY.  THEREFORE, WE'LL TRY TO KEEP THE QUERIES IN UPPER CASE
                  SINCE THE TABLE NAMES AND FIELD NAMES WERE CREATED USING UPPER CASE.
          if(tableName != null)// by checking for a parameter tableName. If its not there
          {                    // the user is coming from the query frame.
            query = "SELECT * FROM " + tableName.toUpperCase();
            qBean.setQuery(" ");
          else
            query =(String)req.getParameter("query");
            qBean.setQuery(query.toUpperCase());
          //System.out.println(query);
                 //boolean value to know where to transfer control
                 //(QueryOutputProccess or QueryOutputProccessUpdate)
          boolean isQuery = false;
                // check if the user hase entered a valid query
                //(SELECT, INSERT, UPDATE, DELETE)
         if (checkQuery(query))
                  //if is a select then get the resuts and store them in the bean
           if ("SELECT".equalsIgnoreCase(query.substring(0,6)))
                    //System.out.println("Its a SELECT query");
                    resultSet = statement.executeQuery(query);
             ResultSetMetaData rsmd = resultSet.getMetaData();
             int numCols = rsmd.getColumnCount();
             qBean.setNumColumns(numCols);
             isQuery = true;
                    for ( int i = 1; i <= numCols; i++)
               qBean.setColumnLabel(rsmd.getColumnLabel(i));
               qBean.setColumnTypeName(rsmd.getColumnTypeName(i));
                    while(resultSet.next())
                      for (int i = 1; i <= numCols; i++)
                        qBean.setResults(resultSet.getString(i));
                  else // if its not a SELECT that means is an INSERT, UPDATE OR DELETE. Perform the operation.
                    System.out.println("Its not a SELECT query");
             statement.executeUpdate(query);
                  session.setAttribute("qBean", qBean); // put the bean back in the session
                  // transfer control to the correct jsp page.
                  //(is different if its a SELECT statement)
           if(isQuery)
                    res.sendRedirect("/scholastic/manager/QueryOutputProcess.jsp");
                  else
                    res.sendRedirect("/scholastic/manager/QueryOutputProcessUpdate.jsp");
         // If the user entered a null query or a bad query
                //(other than SELECT, INSERT, UPDATE, DELETE)
                // then transfer control to an error page indicating the message.
         else
                  //System.out.println("Null or Bad query");
           if(query.length() == 0)  
                    res.sendRedirect("/scholastic/manager/errorQuery.jsp?message=No SQL expression entered");
                  else
             res.sendRedirect("/scholastic/manager/errorQuery.jsp?message=ERROR...Invalid SQL expression entered");
                resultSet.close();
                resultSet = null;
                statement.close();
                statement = null;
                connection.close();
                connection = null;
          catch (SQLException e)
            //if there is an SQL exception get the exception's message
            //and state and transfer control to an error page
    res.sendRedirect("/scholastic/manager/errorException.jsp?state=" + e.getSQLState() + "&message=" + e.getMessage());
          catch( Exception e)
            System.out.println(e);
          finally
            if (resultSet != null)
              try { resultSet.close(); } catch (SQLException e) { ; }
              resultSet = null;
            if (statement != null)
              try { statement.close(); } catch (SQLException e) { ; }
              statement = null;
            if (connection != null)
              try { connection.close(); } catch (SQLException e) { ; }
              connection = null;
       // method for checking if the user hase enter a valid
       // query (SELECT, INSERT, UPDATE, DELETE)
       public boolean checkQuery(String query)
         boolean temp = false;
         if(query.length() > 0 && query.length() > 5)
           if(("SELECT".equalsIgnoreCase(query.substring(0,6))) ||
              ("INSERT".equalsIgnoreCase(query.substring(0,6))) ||
       ("UPDATE".equalsIgnoreCase(query.substring(0,6))) ||
       ("DELETE".equalsIgnoreCase(query.substring(0,6))))
                   temp = true;
        return temp;
    }

    The button calls the control servlet with doGet.
    What is one of the first things you do for doGet?
    QueryBean qBean = new QueryBean(); // a QueryBean object

  • Sql server to Oracle migration using java

    I am doing a project in which i need to create a java application which migrates sql server(2000) db to oracle..kindly help me out

    Thanks for your help..i do not want any third party
    components..i am almost done with the tables
    migration and am trying to figure out about
    procedures..here is a code which does migrate
    tables...hope it helps you too!
    * Copyright Isocra Ltd 2004
    * You can use, modify and freely distribute this file
    as long as you credit Isocra Ltd.
    * There is no explicit or implied guarantee of
    functionality associated with this file, use it at
    your own risk.
    package com.isocra.util;
    import java.sql.DatabaseMetaData;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.PreparedStatement;
    import java.sql.ResultSetMetaData;
    import java.util.Properties;
    import java.io.FileInputStream;
    import java.io.IOException;
    * This class connects to a database and dumps all
    the tables and contents out to stdout in the form
    of
    * a set of SQL executable statements
    ublic class db2sql {
    /** Dump the whole database to an SQL string */
    public static String dumpDB(Properties props) {
    String driverClassName =
    props.getProperty("driver.class");
    String driverURL =
    props.getProperty("driver.url");
    // Default to not having a quote character
    String columnNameQuote =
    props.getProperty("columnName.quoteChar", "");
    DatabaseMetaData dbMetaData = null;
    Connection dbConn = null;
    try {
    Class.forName(driverClassName);
    dbConn =
    DriverManager.getConnection(driverURL, props);
    dbMetaData = dbConn.getMetaData();
    catch( Exception e ) {
    System.err.println("Unable to connect to
    database: "+e);
    return null;
    try {
    StringBuffer result = new StringBuffer();
    String catalog =
    props.getProperty("catalog");
    String schema =
    props.getProperty("schemaPattern");
    String tables =
    props.getProperty("tableName");
    ResultSet rs =
    dbMetaData.getTables(catalog, schema, tables,
    null);
    if (! rs.next()) {
    System.err.println("Unable to find any tables
    matching: catalog="+catalog+" schema="+schema+"
    tables="+tables);
    rs.close();
    lse {
    // Right, we have some tables, so we
    can go to work.
    // the details we have are
    // TABLE_CAT String => table catalog (may be null)
    // TABLE_SCHEM String => table schema
    (may be null)
    // TABLE_NAME String => table name
    // TABLE_TYPE String => table type. Typical types
    are "TABLE", "VIEW", "SYSTEM TABLE", "GLOBAL
    TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM".
    // REMARKS String => explanatory
    comment on the table
    // TYPE_CAT String => the types
    catalog (may be null)
    // TYPE_SCHEM String => the types
    schema (may be null)
    // TYPE_NAME String => type name (may
    be null)
    // SELF_REFERENCING_COL_NAME String
    => name of the designated "identifier" column of a
    typed table (may be null)
    // REF_GENERATION String => specifies
    how values in SELF_REFERENCING_COL_NAME are created.
    Values are "SYSTEM", "USER", "DERIVED". (may be
    null)
    // We will ignore the schema and
    stuff, because people might want to import it
    somewhere else
    // We will also ignore any tables
    that aren't of type TABLE for now.
    // We use a do-while because we've
    already caled rs.next to see if there are any rows
    do {
    String tableName = rs.getString("TABLE_NAME");
    String tableType =
    rs.getString("TABLE_TYPE");
    if
    ("TABLE".equalsIgnoreCase(tableType)) {
    result.append("\n\n--
    "+tableName);
    result.append("\nCREATE TABLE
    "+tableName+" (\n");
    ResultSet tableMetaData =
    dbMetaData.getColumns(null, null, tableName, "%");
    boolean firstLine = true;
    while (tableMetaData.next()) {
    if (firstLine) {
    firstLine = false;
    } else {
    // If we're not the first line, then finish
    the previous line with a comma
    result.append(",\n");
    String columnName =
    tableMetaData.getString("COLUMN_NAME");
    String columnType =
    tableMetaData.getString("TYPE_NAME");
    // WARNING: this may give
    daft answers for some types on some databases (eg
    JDBC-ODBC link)
    int columnSize =
    tableMetaData.getInt("COLUMN_SIZE");
    String nullable =
    tableMetaData.getString("IS_NULLABLE");
    String nullString =
    "NULL";
    if
    ("NO".equalsIgnoreCase(nullable)) {
    nullString = "NOT
    NULL";
    result.append("
    "+columnNameQuote+columnName+columnNameQuote+"
    "+columnType+" ("+columnSize+")"+" "+nullString);
    tableMetaData.close();
    // Now we need to put the
    primary key constraint
    try {
    ResultSet primaryKeys =
    dbMetaData.getPrimaryKeys(catalog, schema,
    tableName);
    // What we might get:
    // TABLE_CAT String => table catalog (may be null)
    // TABLE_SCHEM String =>
    table schema (may be null)
    // TABLE_NAME String =>
    table name
    // COLUMN_NAME String =>
    column name
    // KEY_SEQ short =>
    sequence number within primary key
    // PK_NAME String =>
    primary key name (may be null)
    String primaryKeyName =
    null;
    StringBuffer
    primaryKeyColumns = new StringBuffer();
    while
    (primaryKeys.next()) {
    String thisKeyName =
    primaryKeys.getString("PK_NAME");
    if ((thisKeyName !=
    null && primaryKeyName == null)
    ||
    (thisKeyName == null && primaryKeyName != null)
    ||
    (thisKeyName != null && !
    thisKeyName.equals(primaryKeyName))
    ||
    (primaryKeyName != null && !
    primaryKeyName.equals(thisKeyName))) {
    // the keynames
    aren't the same, so output all that we have so far
    (if anything)
    // and start a
    new primary key entry
    if
    (primaryKeyColumns.length() > 0) {
    // There's
    something to output
    esult.append(",\n PRIMARY KEY ");
    if
    (primaryKeyName != null) {
    result.append(primaryKeyName); }
    esult.append("("+primaryKeyColumns.toString()+")");
    // Start again with the new name
    primaryKeyColumns
    = new StringBuffer();
    primaryKeyName =
    thisKeyName;
    // Now append the column
    if
    (primaryKeyColumns.length() > 0) {
    rimaryKeyColumns.append(", ");
    primaryKeyColumns.append(primaryKeys.getString("COLUMN
    _NAME"));
    if (primaryKeyColumns.length() > 0) {
    // There's something
    to output
    result.append(",\n
    PRIMARY KEY ");
    if (primaryKeyName !=
    null) { result.append(primaryKeyName); }
    result.append("
    ("+primaryKeyColumns.toString()+")");
    tch (SQLException e) {
    // NB you will get this
    exception with the JDBC-ODBC link because it says
    // [Microsoft][ODBC
    Driver Manager] Driver does not support this
    function
    ystem.err.println("Unable to get primary keys for
    table "+tableName+" because "+e);
    result.append("\n);\n");
    // Right, we have a table, so
    we can go and dump it
    dumpTable(dbConn, result,
    tableName);
    hile (rs.next());
    rs.close();
    dbConn.close();
    return result.toString();
    } catch (SQLException e) {
    e.printStackTrace(); //To change body of catch
    statement use Options | File Templates.
    return null;
    /** dump this particular table to the string
    buffer */
    private static void dumpTable(Connection dbConn,
    StringBuffer result, String tableName) {
    try {
    // First we output the create table stuff
    PreparedStatement stmt =
    dbConn.prepareStatement("SELECT * FROM "+tableName);
    ResultSet rs = stmt.executeQuery();
    ResultSetMetaData metaData = rs.getMetaData();
    int columnCount =
    metaData.getColumnCount();
    // Now we can output the actual data
    result.append("\n\n-- Data for "+tableName+"\n");
    while (rs.next()) {
    result.append("INSERT INTO "+tableName+" VALUES
    for (int i=0; i<columnCount; i++) {
    if (i > 0) {
    result.append(", ");
    Object value = rs.getObject(i+1);
    if (value == null) {
    result.append("NULL");
    lse {
    String outputValue =
    value.toString();
    outputValue =
    outputValue.replaceAll("'","\\'");
    esult.append("'"+outputValue+"'");
    result.append(");\n");
    rs.close();
    stmt.close();
    } catch (SQLException e) {
    System.err.println("Unable to dump table
    "+tableName+" because: "+e);
    /** Main method takes arguments for connection to
    JDBC etc. */
    public static void main(String[] args) {
    if (args.length != 1) {
    System.err.println("usage: db2sql <property
    file>");
    // Right so there's one argument, we assume it's a
    property file
    // so lets open it
    Properties props = new Properties();
    try {
    props.load(new FileInputStream(args[0]));
    System.out.println(dumpDB(props));
    } catch (IOException e) {
    System.err.println("Unable to open
    property file: "+args[0]+" exception: "+e);
    }hi,
    Thanks i used your coding and it works well...
    i also used other thing i inserting the queries and values in another schema with primary and foreign keys.. it works well..
    but problem is i cannot retrieve the unique constraint and other check constraint..
    i cannot insert it..
    and also i cannot create table in order i create the original..
    because the retrieve query s values display based on ascending order i want display query in creation time...
    because when i foreign keys .. the references in available before i create the table..that means a(table name) followed b(table name) .. a(table name) has contain foreign key of b(table name) .. but b (table name) not yet to create .. is possible.. to retrieve based creation time...

Maybe you are looking for

  • Apple TV is not connecting to WiFi all of the sudden

    My AT has been working perfectly fine until I turned it on today. It said I needed to connect to a network. So I go to connect and I keep getting an error message. I reset my WiFi twice and my Apple TV multiple times. I have no idea what's going on.

  • How to prevent the code viewing of jsp files

    hello friends How to prevent the code viewing on directly opening .jsp files at the server side Thanks in advance

  • Parsing "~" in the File class

    On the same (Linux) computer, sometimes, new java.io.File("~").isDirectory() returns 'true' and, sometimes, it doesn't. To be clearer, in some programs it returns true and in other programs it doesn't. This is driving me crazy! PS. I know I should be

  • How to display archive link picture in pdf

    Hi, Experts   I create a pdf form using tcode SFP, and create a graphics element in the form, but i don't want to use the MIME object to disaplay,because our pictures are archive link. How to display archive link picture in pdf form? Thanks you very

  • Tables from prog

    hi, What are the ways to find out the tables used in the program? regards, kb