Autogenerated key

I can connect to my database through jdbc, run queries, etc. Now I need to be able to add rows to a table. However, I have a primary key that is an autogenerated number, and I don't know what to pass in the variable.
My update string is as follows:
=============================================
UPDATE_STRING = "INSERT INTO PPAL_LOGS " +
"VALUES ('" + LOG_SEQ_ID + "', '" + PPA_NBR + "', '" + FILE_TIME_STAMP + "', '" + DATE_PROCESSED +
"', '" + PROCESSED_FLAG + "', '" + FILE_NAME + "')";
=============================================
My autogenerated, numeric key is LOG_SEQ_ID. What should the value of this be? Thanks for your help!

Assuming that LOG_SEQ_ID the name of the primary key column in you PPAL_LOGS table, and is also the name of an Oracle sequence, you have two options. First, if you need the key at the same time you insert a row into your table in order to insert rows into a child table, then allocate a sequence by executing the following SQL statement before your insert:
Integer log_seq_id;
ResultSet rset = conn.executeQuery(
"select LOG_SEQ_ID.nextval from DUAL");
rset.next();
log_seq_id = rset.getInteger(1);
then use log_seq_id in your insert statement.
If you don't need to know the value of your LOG_SEQ_ID, or this is a table that you do a lot of loading of external data, then you can create a trigger on the table in the database to automatically allocate a sequence when the LOG_SEQ_ID column is null like so:
create or replace trigger PPAL_LOGS_BIR
before insert on PPAL_LOGS
for each row
begin
if :new.LOG_SEQ_ID is null then
begin
select LOG_SEQ_ID.nextval
into :new.LOG_SEQ_ID
from SYS.DUAL;
exception
when OTHERS then
raise_application_error( -20000,
SQLERRM| |
' on select LOG_SEQ_ID.nextval'| |
' in PPAL_LOGS_BIR' );
end;
end if;
end;
Once a trigger like this is in place, any time you specify a null for LOG_SEQ_ID, the trigger will allocate a new sequence and assign it to the column for you while it is inserting the row into the table.

Similar Messages

  • How to get autogenerated key - special case

    Hi there, here's a really tricky one;
    I have a query as follows below:
    So I insert a product if I cannot find the product, otherwise i do not insert the product. But how can get the autogenerated productConfigId key ?? I know there's a way to get the autogenerated key, but in this case sometimes the key already existed in this database and I do not generate it!
    Is there a way to get the key from the select-subquery OR the autogenerated one, depending on whether it existed or not???
    Very thankful for any answer to this,
    Best regards, AC
    IF NOT EXISTS
    (SELECT productConfigId FROM product WHERE productId = ? AND partQty = ?)
    INSERT INTO product(productId, partQty) VALUES(?, ?)

    Which db are you using?
    Commonly stored procedures are used to return the autogen.id
    - Mark

  • Autogenerated key with Prepared Statement...

    Hi guys,
    i've a question and i need help...
    how can i retrieve autogenerated key with prepared Statement?
    I see examples only about statements...please post me example code..

    where i've to put STATEMENT.RETURN_GENERATED_KEYS?
    I need to use executeUpdate()...I didn't put it anywhere. I just called the getGeneratedKeys() method without using that constant anywhere and it just worked.

  • Retrieving auto inc primary key from entity bean (MySQL DB)

    Hello,
    I searched the forum intensively, but did not find an answer for the following problem.
    I've set up an MySQL database "Location" with two fields (ID, Description), ID is my primary key and I've added the AUTO_INCREMENT flag to this field. This works fine, i can add a row in the table with my entity bean "Location" from my session bean :
    Location l = new Location();
    l.setDescription("at home");
    em.persist(l);
    and even when I ask this location back from the DB, there is no problem :
    Location l = em.find(Location.class,1);
    return l.getDescription();
    The rows in the table increment nicely. The problem however is, that you don't allways know the ID. So I would like to do the following from my session bean:
    Location l = new Location();
    l.setDescription("at home");
    em.persist(l);
    int id = l.getId();
    the getID method allways returns a null object. The row is added in the DB, but the auto incremented ID is not returned to the entity bean!
    I know I could solve this by generating the ID's myself, but one of the strengths of autoincrement should be not to have to do this, no?
    If anyone has a clue how to solve this issue, I would very much appreciate it !
    Michiel
    Edited by: Michiel82 on Dec 6, 2007 6:01 AM

    No reactions so far ... this is a work-around for the issue :
    I've created an additional table sequence with two fields: gen_key and gen_value. Then, in my Location entity bean I can add the following:
    @TableGenerator(
    name="locationGen",
    table="sequence",
    pkColumnName="gen_key",
    valueColumnName="gen_value",
    pkColumnValue="location",
    allocationSize=1
    @Id
    @GeneratedValue(strategy=GenerationType.TABLE,generator="locationGen")
    @Column(name = "id", nullable=false)
    private Short id;
    This generates the primary key in the bussiness logic, but I would like to get the autogenerated key from my MySQL database (see previous post). Is this perhaps not supported by EJB3.0?
    Michiel

  • How to determine the exact database error in JPA?

    For example you are going to add a record in the database which primary already exist
    in one of the records in that table in the database. This will cause an error, but how do
    I know this error in human readable form just like "Same record with the same PK in the
    the table already exist" in JPA.
    My current procedure is that I will first check all the records in the database in that table
    and compare those PK's in the current record, if there is a conflict then I know the error.
    But this procedure is so slow considering there are a lot of records in the database.
    Fetch and compare is so slow.
    Anyone help me on this.

    For example you are going to add a record in the database which primary already existin one of the records in that table in the database. This will cause an error, but how do
    I know this error in human readable form just like "Same record with the same PK in the
    the table already exist" in JPA>
    Why would you do that though? If you're using autogenerated keys it can't occur. If you're using business keys you should be checking for the existence of the key before trying to insert. Any other case is likely to be a bug, so don't do that.

  • Native query. How to get the data...

    Hello everyone!
    I'm struggling to figure out how to extract data from particular columns from DB. Here is what I have...
    A table PersData with columns A, B, C, D and so forth. Also there is an entity represents this table called PersonalData.
    I need to get the data from A and C columns, but I still haven't found a solution how to do this. I know how to exctract an entire row from the PersData table by writing the following code...
    Query query = entityManager.createNativeQuery("SELECT * FROM 'PersData` ", PersonalData.class);
    List<PersonalData> qresult = query.getResultList();
    for(PersonalData item: qresult){
          System.out.println(item.getA());
          ........ But it's inefficient to get values of other columns at the same time.
    I guess that my query should be written smth like this...
    Query query = entityManager.createNativeQuery("SELECT A, C FROM `PersData` ");
    List<PersonalData> qresult = query.getResultList();
    for(PersonalData item: qresult){
          System.out.println(item.getA());
          .....But I got an error java.lang.ClassCastException when I do this for (PersonalData item: qresult). Actually, I understand why it's like this.
    Does anybody know how to get values just from two columns and then use them?

    Oops, my bad. it was about 2 paragraphs further
    down...
    "autoGeneratedKeys - a constant indicating whether
    auto-generated keys should be made available for
    retrieval using the method getGeneratedKeys;"Down in what?
    The following is the docs for the method you posted taken from here - http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html#executeUpdate(java.lang.String, int).
    executeUpdate
    public int executeUpdate(String sql,
    int autoGeneratedKeys)
    throws SQLException
    Executes the given SQL statement and signals the driver with the given flag about whether the auto-generated keys produced by this Statement object should be made available for retrieval.
    Parameters:
    sql - must be an SQL INSERT, UPDATE or DELETE statement or an SQL statement that returns nothing
    autoGeneratedKeys - a flag indicating whether auto-generated keys should be made available for retrieval; one of the following constants: Statement.RETURN_GENERATED_KEYS Statement.NO_GENERATED_KEYS
    Returns:
    either the row count for INSERT, UPDATE or DELETE statements, or 0 for SQL statements that return nothing
    Throws:
    SQLException - if a database access error occurs, the given SQL statement returns a ResultSet object, or the given constant is not one of those allowed
    Since:
    1.4
    I don't see the text you posted in there.
    At the very least there is at least a suggestion that an exception will be or could be thrown because the only way some databases can return an autogenerated key is via a result set.

  • Autonumber In DSP 3.0

    I'm using an Oracle database and need to setup autogenerated keys for my tables. I found some documentation on doing this for DSP 2.5, but I haven't found a similar document for DSP 3.0. Can you help?
    Thanks!
    Jeff

    Never mind...found it in properties when selecting primary key field.

  • Is it possible to load or import 1 journal from file?

    Hi to all,
    We are searching how to load or import from and excel file some journals into the journal table of SAP BPC. As we have seen it is possible to load all the table but not only to add one journal to the table.
    Anybody knows if it is possible to load 1 journal from file into SAP BPC and add it to the table of journals?
    in a standard way or using logic??
    Thanks a lot!!!!

    I don't think that there is a method available to ONLY add 1 Journal record, since the sequence of Journals is an Autogenerated key.  The best way would be to simply add the Journal, so that the appropriate values are logged and tracked accordingly.  The table may be loaded, since the "whole" table has a defined key for the sequence of Journal entered transactions.
    Hope this helps.

  • DataService createItem( ) question

    I've been using DataServices to get a collection and then
    add, modify and delete items from it, and everytime i do this i get
    a refresh for that collection, that way i always have the latest
    changes on the items of the collection.
    Now i am trying to add a single item, without using a fill
    method first, but the thing is that after inserting it to the
    database i can't get an update of the item, because i didn't use a
    fill method before.
    The reason i need this is because the item's ID is not set in
    flex, it is set in java (using hibernate) because it is an
    autogenerated ID, so on Flex the item's ID is always null whereas
    in the database the item is inserted correctly with an
    autogenerated key.
    The problem like i said is that the object in flex remains
    with the null id and i can't find a way to update it automatically,
    so i am wondering if there's anyway to do this, that is to insert a
    new item using DataService.createItem() and then have an automatic
    update so the item on Flex is updated according to the values made
    on the database.
    Any help would be great, thanks

    hello,
    i am having the same problem. did you find a soution yet?
    greets
    robson

  • How to remember login password on a computer

    Happy new year to all of you...
    I had made a application which uses login and password for authentication..this is working fine..Now i want to give one option to remember the login and password for the specific computer..actually i dont have any idea on it..Plz give me some suggestion to solve this problem..i have used jsp for front end with struts framework..
    Thanx in advance..
    Gyan

    This isn't hack safe. If one would hijack another user login, one could just change the username in the cookie value.
    Better create a cookie with a long and autogenerated key or hash and store the key in a DB along the User ID. This makes the guessing for keys of another users hard. You can find here an example: [http://balusc.blogspot.com/2007/03/user-session-filter.html].

  • God d*mn JDBC, getGeneratedKeys does not work.

    I am so mad with the limitation of JDBC 3.0. It's version 3, and years of development, what the h*ll.
    To retrieve the auto generated keys, you have to execute an sql statement. So, if the data needs to be escaped properly, I would use PreparedStatement. Unfortunately, PreparedStatement also only allow you to return generated keys if executeUpdate on sql statement:
    pstmt.executeUpdate(sqlString, ,PreparedStatement.RETURN_GENERATED_KEYS);
    So, that means preparedStatement is no different than statement in this case. So, it's almost unusable.
    Next, there is no support for retriving autogenerated keys if you do thing like using recordset.insertRow().

    >
    I am so mad with the limitation of JDBC 3.0. It's
    version 3, and years of development, what the h*ll.
    To retrieve the auto generated keys, you have to
    execute an sql statement. So, if the data needs to be
    escaped properly, I would use PreparedStatement.
    Unfortunately, PreparedStatement also only allow you
    to return generated keys if executeUpdate on sql
    statement:
    pstmt.executeUpdate(sqlString,
    ,PreparedStatement.RETURN_GENERATED_KEYS);
    So, that means preparedStatement is no different than
    statement in this case. So, it's almost unusable.
    Next, there is no support for retriving autogenerated
    keys if you do thing like using recordset.insertRow().3 tier applications can't use updatable result sets. Only smaller applications can use this.
    The JDBC at least allows for user comment and I think it is part of the JCP process so you can join as a member and offer you input for the next version.

  • Reading large lob data from SQL

    I gotta be missing something, but don't see what.  Have seen postings on this topic for years, and the answer is always the same, but I've done all those things.
    I have a CF script that grabs a webpage via CFHTTP, and stores its content in a SQL Server 2008 table in a TEXT datatype.  It also stores at the time of the INSERT the value of the CF expression len(cfhttp.filecontent) in another column (BIGINT).
    Another scripts comes along and tries to do some analysis, so it does a SELECT of the data. The most it ever gets back is 64,000 bytes. It displays the value that was stored as the length during the insert, the current datalength as reported by SQL, and the datalength of the variable in the CF resutls set from the query.  The data is definitely in the database.  I can also do a query in SSMS with a LIKE clause that finds "/HTML" in the data, which would also indicate the all of the data is there.
    Both scripts use the same datasource. The datasource is setup (correctly I believe) as:
    Login Timeout (sec)
    CLOB
        -- Enable long text retrieval (CLOB).
    BLOB
        -- Enable binary large object retrieval (BLOB).
    Long Text Buffer (chr)
    Blob Buffer(bytes)
    Disable Autogenerated Keys
    I cannot think of any other CF admin paramaters to change.  This happens on multiple CF servers across multiple versions (8, 9 , 10) of CF.
    The code that does the retrieval is:
    <cfquery name="results"  datasource="talbot_exsto">
    SELECT  page_text,page_size ,datalength(page_text) AS dblen
    FROM urlcheck..urlcheck_results WITH (nolock)
    WHERE Result_ID=#url.resultID#
    </cfquery>
    #results.page_size# bytes in http results, #results.dblen# bytes in database,
    #len(results.page_text)# bytes in ColdFusion resultset
    for record #url.resultID#
    Which outputs:
    108016 bytes in http results, 108001 bytes in database, 64000 bytes in ColdFusion resultset for record 1774479
    What have I missed?
    thanks everone,
    Reed

    Tried a few more variations on admin settings, no luck.  Anyone have any ideas?
    thanks
    reed

  • GetGeneratedKeys() not supported in 9.2.0.1?

    I am using the latest 9.2.0.1 thin driver (ojdbc14.jar). When I try to execute an insert statement and retrieve an autogenerated key I get an exception which tells me that the function is not supported. I know it is SQL3 and rather new, so I fear this function is indeed not implemented. But this should be stated in the docs. Has anyone more information or tried this before?

    Hi,
    This seems to work fine for me when I run your query.
    My Db info is as follows:
    BANNER
    Oracle9i Enterprise Edition Release 9.2.0.6.0 - 64bit Production
    PL/SQL Release 9.2.0.6.0 - Production
    CORE 9.2.0.6.0 Production
    TNS for HPUX: Version 9.2.0.6.0 - Production
    NLSRTL Version 9.2.0.6.0 - Production
    When I run your query the output I get is:
    SURNAME
    NOVIKOVA
    ANTONOVA
    This proves that there are no issues with your query. I see you are also running Oracle 9i R2, which is good as this was when the XML functionality first appeared in the Db.
    I think the likely issue is that you do not have the XML functionality correctly configured for you Db, I do believe that there is something you need to have enabled through Enterprise Manager before you can start using Oracle's XML functionality.
    I'm sorry to be vague about this, but DB configuration is not my area of expertise. I will have a look around for you and see what I can dig up, but in the mean time, if you have access to a DBA, they may be able to help you out a bit.
    I hope this helps for now,
    Cj

  • ORACLE - ReturnGeneratedKeys

    Hi All,
    Any Help is greatly appreciated..
    I have a problem with AutoGenerated Key in ORACLE JDBC..
    I am using Weblogic 8.1. with service pack 3. I am using Bea's Type 4 JDBC Driver . (JDBC 3.0).
    When i retrieveing Auto Generated Key, Its Returning ROW ID(SOME HEXADECIMAL VALUE) of the
    Inserted Row. But If i use the same method ( getGeneratedKeys()) with SQL Server Databsae , JDBC returning Identity column value( sequence id). Please clarify me whether Oracle JDBC Driver can return sequence Id ( as Identity Column in SQL Server ). Is there any option to get generated sequence id in the table where i inserted a row. Please help me..
    Here is my table :
    USERID USERNAME
    (Auto Increment column)
    ====================================
    90 Raja
    91 Laddu
    When i use SQL Server , AutoGeneratedKey Returning Inserted USERID value as generated key.
    When i use Oracle, Its Returning ROW ID of the inserted record. My requiremnt is to get the generated Sequence ( 92 here) . Please help me and clarify me whether can i get the generated Sequence or not.
    Regards
    Raja

    hmmm, if i understand you correctly when you use: getGeneratedKeys(), that command in java does not work properly. well, I tried that also before, and it didn't work. what i had to end up doing is just use the ResultSet statment. something like this:
    String sql = "sql statement here";
    ResultSet rs = SqlCode.query(sql)  // just encapsulating all the code to do a query
    while(rs.next()) {
          id = rs.getInt("primaryKey");  // in the peranthasis goes the column name of the key you want to retrieve.
    }

  • ORACLE - AutoGeneratedKeys

    Hi All,
    Any Help is greatly appreciated..
    I have a problem with AutoGenerated Key in ORACLE JDBC..
    I am using Weblogic 8.1. with service pack 3. I am using Bea's Type 4 JDBC Driver . (JDBC 3.0).
    When i retrieveing Auto Generated Key, Its Returning ROW ID(SOME HEXADECIMAL VALUE) of the
    Inserted Row. But If i use the same method ( getGeneratedKeys()) with SQL Server Databsae , JDBC returning Identity column value( sequence id). Please clarify me whether Oracle JDBC Driver can return sequence Id ( as Identity Column in SQL Server ). Is there any option to get generated sequence id in the table where i inserted a row. Please help me..
    Here is my table :
    USERID USERNAME
    (Auto Increment column)
    ====================================
    90 Raja
    91 Laddu
    When i use SQL Server , AutoGeneratedKey Returning Inserted USERID value as generated key.
    When i use Oracle, Its Returning ROW ID of the inserted record. My requiremnt is to get the generated Sequence ( 92 here) . Please help me and clarify me whether can i get the generated Sequence or not.
    Regards
    Raja

    No, the Oracle JDBC driver does not support getting generated keys. (There's no guarantee that your schema uses sequences, after all.)
    What you should do is select the current sequence value from dual before doing an INSERT. That way you're guaranteed that no other use will interfere with your transaction.

Maybe you are looking for