Re-using statement objects

Hi,
I am new to jdbc and sql in Java. So this is my question.
If I want to to a select statement and depending on the result a second select, can I do this on the same statement object, or do I have to create a new one? And what about the resultset? Can you re-use this? And do you always close this statement after using it, or can you just close it when the program finishes?
My code is something like this :
Connection con = .....
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(blablabla...);
if (rs.next() = ...)
ResultSet rs = stmt.executeQuery(blablabla);
}

If I want to to a select statement and depending on
the result a second select, can I do this on the same
statement object, or do I have to create a new one?You can reuse your first statement and execute another query with it. But this would close your first resultset. If you want to use two resultsets at the same time, they must be created by different statements.
Note that not all combinations of DBMS / driver support different active statements in 1 connection. In that case you would use a second connection for the second statement.
And what about the resultset? Can you re-use this?You created a simple statement. So you can only position in it downwards by next() and retrieve values. If you execute another query by the same statement, your statement will close the first resultset and return a new one.
And do you always close this statement after using it, or
can you just close it when the program finishes?If you close it, you must create a new one if you need it again.
No problem to let it remain open.
At the end of your program then close them all in the right order:
1. resultset (if still remained unclosed)
2. statement (if still remained unclosed)
3. connection (if still remained unclosed)

Similar Messages

  • How to use Statement objects?

    Each query execution needs seperate Statement objects..
    Or Single statement object is enough to execute all the queries in a program..
    I am executing 6 queries in a program..
    For this i need to create 6 statement objects or one is enough?
    Regards

    one per query would be my rule, because i only keep statements around in a short method context. i close them after i'm done with them in a finally block, along with the result set they generate.
    %

  • Using Date objects in SQL statements

    Hi, I am wondering if it is possible to use Date objects while trying to retrieve entries from an access database with fields set as "Date/Time" fields, as opposed to "Text"? If so, do I need to reformat it before inserting it into the SQL statement, or can I just leave it as a Date object, and call up the variable name?
    For example - "SELECT * FROM database WHERE startDate = ' " + dateObject + ' ". And do i need quotes round this value?
    Thanks in advance.

    I had some problems by just fetching a date and pushing it back to a MS SQL Database.
    I used the following reformating step to fix it:
    if (o instanceof Timestamp)
    String time = o.toString().substring(8,10)+"."+o.toString().substring(5,7)+"."+o.toString().substring(0,4)+" "+o.toString().substring(11,19);
    ht.put(columnName, time);
    o is the object i receve from the select statement and ht is a Hashtable where i put my data.
    To write the data back i now can use:
    UPDATE table SET columnname = 'valueOfColumn'
    This means i use the value i created above in Quotes to write it back.
    Format of Timestamp.toString() is something like yyyy-mm-dd hh:mm:ss.xx
    Format used by MS SQL (and i think by Access to) 'dd.mm.yyyy hh:mm:ss'

  • Slideshow Using Multi-State Objects

    Hi,
    I created a slideshow in an Indesign document using multi-state objects. The slideshow has foward and backward buttons to navigate the slideshow. The slideshow works fine in Indesign but when I export the document as an intereactive pdf, the slideshow no longers works. What am I doing wrong? I'm using Indesign CS 5.5.
    Thank you,
    Kristie

    What you're doing wrong is expecting it to work. MSOs are for SWF and DPS output only.
    The only workaround is doing it in its own file, exporting to SWF and placing that in the PDF.
    Bob

  • Can I assign the text in a multi-state object?

    I want to assign InCopy files to the captions that are part of a slideshow, but I can't seem to create assignments for the text boxes that are in a multi-state object. Is this possible?

    Currently there is no capability to add text frames withing an MSO to an InCopy assignment. There is limited support for this edit workflow when using solutions such as WoodWing or K4. Please make sure to fill out the feature request form: https://www.adobe.com/cfusion/mmform/index.cfm?name=wishform so that we can capture the demand for this function.

  • Can I use C++ objects as Host variables in Pro*C++

    Hi,
    I have a C++ object in my Pro*C++ program. The objects has
    members representing all the fields of a oracle table record.
    e.g. For a table TEST_PRODUCT ( product_id, name),
    the C++ class is :
    class prd
    public:
    int id;
    char name[50];
    Can I use the Object of this class as a Host Variable ? In SQL
    select query , I want to directly fetch record into this object.
    When I declare this object within EXEC SQL BEGIN DECLARE SECTION
    and END DECLARE SECTION , it gives me compilation error.
    Is that supported by Pro*C++ ? If yes, how to do it?
    Pls help.
    Thanks

    I find it easier to decalre a local variable in the EXEC SQL
    block and then assign that to your class variable at the end of
    the statement. It makes it easy to check for nulls and db
    errors without affecting the C++ object.
    PT

  • Can't Create Statement Object - Help

    Hi:
    I'm using NetBeans 5.0
    which is pointing at:
    Java\jdk1.5.0_07
    The IDE can't see the Statement object:
    'cannot find symbol Statement'.
    It won't compile.
    I've included: import java.* at the top of the file.
    It's not having a problem creating the connection object, just the Statement object.
    Can you tell me what I'm missing or what I need to make the IDE 'see' the Statement type?
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
    oCn = java.sql.DriverManager.getConnection(getConnectionUrl), userName,password);
    Statement stmt = oCn.createStatement(); //<<-- IDE cant' see this

    Never mind. I figured it out:
    import java.sql.
    In general, these forums are GREAT!!
    Thanks very much for all the answers you 've given me.
    You're better than ANY support team:o)

  • How can i execute multiple database operations using multiple objects

    i have data in files which i need to read/parse and insert/update the database. can someone tell me how can i read multiple statements at a time and process using multiple objects.

    This doesn't seem like too much of a JDBC question or at least the answer as I see it isn't unique or specific to JDBC.
    If you want to run multiple processes within your single program then you need to use Java threads. I would recommend you read up on how to properly code Java threads and if you have questions unique to your multi-threaded JDBC implementation come back and ask those questions.
    You may also want tot take advantage of a transaction manager that includes a database connection pool that will handle most of the complexity for you. Depending on the flexibility of your architecture you may not have to do any thread coding at all when using a transaction manager.

  • List the used ABAP objects

    Hi all,
    I'm looking for a standard tool to list the used ABAP objects (Reports, Include, Function Group, CLASSes) in a time
    frame of one year or at least since the start-up.
    My goal is the identification of the obsolete custom developments to dismiss it.
    I have found the transaction SCOV but the goal of this transaction is the estimation of the code
    coverage during the test.
    Anyone can help me?
    Thanks in advantage

    This kind of data is stored in table MONI - Monitor table MONI (summarized cluster table!) and in some files of the application server (in the OS behind SAP)
    - Transaction STAT or ST03n use data stored in these tables
    - Some FM like [SAPWL_SERVLIST_GET_LIST|https://www.sdn.sap.com/irj/scn/advancedsearch?cat=sdn_all&query=sapwl_servlist_get_list&adv=false&sortby=cm_rnd_rankvalue] and  [SAPWL_WORKLOAD_GET_STATISTIC|https://www.sdn.sap.com/irj/scn/advancedsearch?query=sapwl_workload_get_statistic&cat=sdn_all] may be used to get the data from each application server
    (click on the links to get more information and samples on how to use these FM)
    Regards

  • Multi-State Object Change Speed

    How can I adjust the speed and style how the multi-state object changes its states? I find the fade to be too long. Any ways that that can be shortened?

    Select the MSO and use the options in the Folio Overlays panel.

  • DPS HTML to activate multi state object

    Is there a way to have an HTML asset placed in a DPS folio, to activate a specific state of a multi state object?

    I don't think there is a way to use hyperlinks to change an MSO's state.
    Two approaches you might try:
    1 - Lose the MSO and create it as an html overlay and use jQuery to create a similar MSO change state experience
    2 - Try overlaying a blank button on your html link and use that to change the MSO state

  • Buttons under a state object

    How can I make inactive, a button, in a state object, which is located under?

    @diametrabi – can you elaborate your question a bit more?
    A sceen shot could help. You could attach it when using the forum software:
    Uwe

  • 'duplicate column name'-Exception when using identical objects

    Hi all,
    we're currently experiencing problems when using one single object instance for two different members of a mapped class. Here is an excerpt from our ToplinkMapping.java which shows the relevant parts:
    public ClassDescriptor buildQuotationDefDescriptor() {
    RelationalDescriptor descriptor = new RelationalDescriptor();
    descriptor.descriptorIsAggregate();
    descriptor.setJavaClass(de.hvb.ha.data.QuotationDef.class);
    // Descriptor Properties.
    descriptor.setAlias("QuotationDef");
    AggregateObjectMapping commonQtyMapping = new AggregateObjectMapping();
    commonQtyMapping.setAttributeName("commonQty");
    commonQtyMapping.setReferenceClass(de.hvb.ha.data.type.VolumeDT.class);
    commonQtyMapping.setIsNullAllowed(false);
    commonQtyMapping.addFieldNameTranslation("commonQty_value->DIRECT", "value->DIRECT");
    descriptor.addMapping(commonQtyMapping);     
    AggregateObjectMapping wideningQtyMapping = new AggregateObjectMapping();
    wideningQtyMapping.setAttributeName("wideningQty");
    wideningQtyMapping.setReferenceClass(de.hvb.ha.data.type.VolumeDT.class);
    wideningQtyMapping.setIsNullAllowed(false);
    wideningQtyMapping.addFieldNameTranslation("wideningQty_value->DIRECT", "value->DIRECT");
    descriptor.addMapping(wideningQtyMapping);
    well, if we now assign one object-instance of VolumeDT to both members, i.e. like:
    VolumeDT vol = new VolumeDT();
    quotationDef.commonQty = vol;
    quotationDef.wideningQty = vol;
    we end up in the mentioned SQL-Exception, because toplink produces the following SQL-Statement:
    UPDATE T_QUOTATIONTARGET SET WIDENING_QUANTITY = 0.0, WIDENING_QUANTITY = 0.0 WHERE …
    but we've expected something like:
    UPDATE T_QUOTATIONTARGET SET COMMON_QUANTITY = 0.0, WIDENING_QUANTITY = 0.0 WHERE …
    Any idea we can prevent this behavior and still use one object-reference for both members??
    Appreciate any help!

    Thanks for the reply but unfortunately the mentioned change didn't fixed the problem. The sql-statement produced by toplink still looks like the one mentioned above. Moreover, the mentioned change couldn't be managed by the Workbench (which we use in the project to create the mappings), could it?
    We currently use TopLink Version 10.1.3.3.
    Since you've asked I post the relevant parts of the Parent-Mapping (and again its Parent), so sorry for the verbose post:
    public ClassDescriptor buildQuotationORMWrapperDescriptor() {
    RelationalDescriptor descriptor = new RelationalDescriptor();
    descriptor.setJavaClass(de.hvb.ha.server.businessobjects.techapi.instrument.toplink.quotation.QuotationORMWrapper.class);
    descriptor.addTableName("T_QUOTATION");
    descriptor.addPrimaryKeyFieldName("T_QUOTATION.SEQ_KEY");
    // Descriptor Properties.
    descriptor.useSoftCacheWeakIdentityMap();
    descriptor.setIdentityMapSize(300);
    descriptor.useRemoteSoftCacheWeakIdentityMap();
    descriptor.setRemoteIdentityMapSize(300);
    descriptor.setSequenceNumberFieldName("T_QUOTATION.SEQ_KEY");
    descriptor.setSequenceNumberName("Quotation");
    descriptor.setAlias("QuotationORMWrapper");     
    // Query Manager.
    descriptor.getQueryManager().checkCacheForDoesExist();
    OneToManyMapping quotationDefsMapping = new OneToManyMapping();
    quotationDefsMapping.setAttributeName("quotationDefs");
    quotationDefsMapping.setReferenceClass(de.hvb.ha.server.businessobjects.techapi.instrument.toplink.quotation.QuotationDefORMWrapper.class);
    quotationDefsMapping.dontUseIndirection();
    quotationDefsMapping.privateOwnedRelationship();
    quotationDefsMapping.useCollectionClass(java.util.ArrayList.class);
    quotationDefsMapping.addAscendingOrdering("orderBy");
    quotationDefsMapping.addTargetForeignKeyFieldName("T_QUOTATIONTARGET.SEQ_KEY", "T_QUOTATION.SEQ_KEY");
    descriptor.addMapping(quotationDefsMapping);
    and now the parent of QuotationORMWrapper:
    public ClassDescriptor buildPersistentInstrumentDescriptor() {
    RelationalDescriptor descriptor = new RelationalDescriptor();
    descriptor.setJavaClass(de.hvb.ha.server.businessobjects.techapi.instrument.toplink.PersistentInstrument.class);
    descriptor.addTableName("T_INSTRUMENT");
    descriptor.addPrimaryKeyFieldName("T_INSTRUMENT.INSTR_ID");
    descriptor.addPrimaryKeyFieldName("T_INSTRUMENT.INSTR_KEYTYPE");     
    // Descriptor Properties.
    descriptor.useSoftCacheWeakIdentityMap();
    descriptor.setIdentityMapSize(300);
    descriptor.useRemoteSoftCacheWeakIdentityMap();
    descriptor.setRemoteIdentityMapSize(300);
    descriptor.setAlias("PersistentInstrument");
    OneToOneMapping quotationMapping = new OneToOneMapping();
    quotationMapping.setAttributeName("quotation");
    quotationMapping.setReferenceClass(de.hvb.ha.server.businessobjects.techapi.instrument.toplink.quotation.QuotationORMWrapper.class);
    quotationMapping.useBasicIndirection();
    quotationMapping.privateOwnedRelationship();
    quotationMapping.addTargetForeignKeyFieldName("T_QUOTATION.INSTR_ID", "T_INSTRUMENT.INSTR_ID");
    quotationMapping.addTargetForeignKeyFieldName("T_QUOTATION.INSTR_KEYTYPE", "T_INSTRUMENT.INSTR_KEYTYPE");
    descriptor.addMapping(quotationMapping)
    I hope I don't missed any relevant parts. By the way, where could I log a bug for this issue and can it be considered a bug?
    Thanks in advance!
    Message was edited by:
    user630939

  • "Overlapping ResultSets" from one Statement Object

    I'm using Hypersonic database and retrieving data using JDBC.
    I create a single Statement object which I use to return multiple ResultSets.
    e.g.
    conn = DriverManager.getConnection(url.getText(), "sa", "p");
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    customerRS = stmt.executeQuery(sql1);
    productRS = stmt.executeQuery(sql2);
    If use the second ResultSet before the first has been fully traversed, I loose the data in the first.
    This comes about because I'm changing a DefaultTableModel from reading the ResultSet into an array to pulling the data out of the ResultSet in the getValueAt as and when required.
    I have multiple jtables in my app, when I pulled all the data out of the ResultSet into an array and then returned the array values on the getValueAt(), every thing was fine, now I try and have the ResultSet hang around, I'm getting "empty" tables displayed in my app.
    So, my question, do I need a Statement object for every RecordSet I want to access in this way or is there a bug in the JDBC driver I am using ?
    regards,
    dave

    First, I believe the problem you are experiencing is in the OBDC:JDBC bridge. If you are using Hypersonic drivers, you might look at upgrading.
    If the driver will allow it, you can actually return multiple resultsets.
    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2B%22multiple+resultsets%22&col=javaforums

  • 10g: Initialize State object?

    I like the idea of using the State object on the Page to manage State. I've coded the EventHandler to read the parameters and store them on the state, and I see how to read them back from the state when re-rendering the page. My object model also knows what the default selections should be when the user first opens the page, but I don't know how to get these into the State before the user makes their first set of selections and submits those to the EventHandler.
    This seems to be related to the suggestion in the documentation that one "should always gracefully handle the absence of a State object." I'd rather not have to code the equivalent of "selectedValue = (uix:pageState == null ? getDefault : uix:pageState.selectedValue)" throughout the forms. What would be the most elegant way to put "if uix:pageState == null then pageState = getDefaultState" in the page? I was thinking about just creating a defaultState property on my dataSource and using that.
    Am I barking up the wrong tree? Are there recommended patterns to "gracefully handle the absence of a State object"?

    I'll ask around tomorrow.

Maybe you are looking for