Last_insert_id()

Hi all,
I am using container manager entity beans.
I have inserted a new row into my mysql database, primary id is of auto_increment and I am trying to retrieve the new id created.
I have used em.createQuery("select last_insert_id()") , and I get a bunch of errors.
Would anyone be able to help me or help me get on the right path.
Regards,
Deniz

run-tool:
Apr 27, 2007 2:41:57 PM com.sun.enterprise.appclient.MainWithModuleSupport <init>
WARNING: ACC003: Application threw an exception.
javax.ejb.EJBException: nested exception is: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.RemoteException
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.RemoteException
at com.sun.corba.ee.impl.javax.rmi.CORBA.Util.mapSystemException(Util.java:188)
at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.privateInvoke(StubInvocationHandlerImpl.java:172)
at com.sun.corba.ee.impl.presentation.rmi.StubInvocationHandlerImpl.invoke(StubInvocationHandlerImpl.java:119)
at com.sun.corba.ee.impl.presentation.rmi.bcel.BCELStubBase.invoke(BCELStubBase.java:197)
at office.__CustomerFacadeRemote_Remote_DynamicStub.getLastId(__CustomerFacadeRemote_Remote_DynamicStub.java)
at office._CustomerFacadeRemote_Wrapper.getLastId(office._CustomerFacadeRemote_Wrapper.java)
at shop.Main.main(Main.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:589)
at com.sun.enterprise.util.Utility.invokeApplicationMain(Utility.java:232)
at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:329)
at com.sun.enterprise.appclient.Main.main(Main.java:180)
Caused by: java.rmi.RemoteException
at com.sun.enterprise.iiop.POAProtocolMgr.mapException(POAProtocolMgr.java:234)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1280)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:197)
at com.sun.ejb.containers.EJBObjectInvocationHandlerDelegate.invoke(EJBObjectInvocationHandlerDelegate.java:110)
at $Proxy69.getLastId(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:589)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:121)
at com.sun.corba.ee.impl.protocol.CorbaServerRequestDispatcherImpl.dispatchToServant(CorbaServerRequestDispatcherImpl.java:650)
at com.sun.corba.ee.impl.protocol.CorbaServerRequestDispatcherImpl.dispatch(CorbaServerRequestDispatcherImpl.java:193)
at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleRequestRequest(CorbaMessageMediatorImpl.java:1705)
at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleRequest(CorbaMessageMediatorImpl.java:1565)
at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleInput(CorbaMessageMediatorImpl.java:947)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:178)
at com.sun.corba.ee.impl.protocol.CorbaMessageMediatorImpl.handleRequest(CorbaMessageMediatorImpl.java:717)
at com.sun.corba.ee.impl.transport.SocketOrChannelConnectionImpl.dispatch(SocketOrChannelConnectionImpl.java:473)
at com.sun.corba.ee.impl.transport.SocketOrChannelConnectionImpl.doWork(SocketOrChannelConnectionImpl.java:1270)
at com.sun.corba.ee.impl.orbutil.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:479)
javax.ejb.EJBException: nested exception is: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.RemoteException
at office._CustomerFacadeRemote_Wrapper.getLastId(office._CustomerFacadeRemote_Wrapper.java)
at shop.Main.main(Main.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:589)
at com.sun.enterprise.util.Utility.invokeApplicationMain(Utility.java:232)
at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:329)
at com.sun.enterprise.appclient.Main.main(Main.java:180)
Exception in thread "main" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:340)
at com.sun.enterprise.appclient.Main.main(Main.java:180)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:589)
at com.sun.enterprise.util.Utility.invokeApplicationMain(Utility.java:232)
at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:329)
... 1 more
Caused by: javax.ejb.EJBException: nested exception is: java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.RemoteException
at office._CustomerFacadeRemote_Wrapper.getLastId(office._CustomerFacadeRemote_Wrapper.java)
at shop.Main.main(Main.java:68)
... 7 more
Java Result: 1
run-jar:
run-display-browser:
run:
BUILD SUCCESSFUL (total time: 8 seconds)

Similar Messages

  • MySQL Transaction last_insert_id

    Can anyone tell me how to get the last inserted id when in transaction ?
    I have to do inserts in several tables.
    Problem is when inserting into one table my auto_increment id of the table should be used as a foreign key in the next table and so on.
    I think when in transaction I cannot query for the last_insert_id with my existing connection, because it is not yet committed.
    Is there a (standard) way to solve this problem ?

    It depends what you mean by "standard". Standard to MySQL, you could use this:
    SELECT LAST_INSERT_ID();
    Some vendors provide driver-specific extensions to allow retrieval of such a value.
    If you want a more portable solution then you could create a stored procedure to carry out the insert and have it return the ID as an out value.
    There are other techniques, but I don't think there's a "standard" way to retrieve this value on insert, because this isn't a "standard" SQL feature in the first place.
    Oh, and as far as I know most users couldn't care less about the duke dollars thing - they're not actually useful in any way.
    Patience is a virtue.
    Dave.

  • How can you update to the same row when........

    Ok so now I have Session variables working correctly and come
    to find out that my host creates a new DB connection for each page
    displayed. So the Last_Insert_ID() will not work because of the new
    connection each time. What are my options for updating a row after
    an insert. I am using MySQL 4.1 and CF 7.
    Thanks
    Shane

    Hi Sankalan, thanks for your input. I am trying now to get
    the following code to work on the Insert page and keep getting this
    error "Element AD_ID is undefined in LASTINSERTID"
    Not sure what is wrong but I have tried many different
    changes and it still will not clear the error.
    Any help would be great.
    Shane
    <cfparam name="SESSION.Last_Insert_id" default="1">
    <cflock scope="Session" timeout="30" type="Exclusive">
    <cfset SESSION.LAST_INSERT_ID=#LastInsertid.AD_ID#>
    </cflock>
    <cfquery name="LastInsertID" datasource="saa">
    SELECT LAST_INSERT_ID() AS AD_ID;
    </cfquery>
    <cfoutput>#LastInsertid.AD_ID#</cfoutput>

  • Anyone know how to insert to multiple tables on Dreamweaver?

    Hey everyone,
    I'm a bit of a newbie at PHP and am trying to create my first "dynamic" site.  I have a registration table with fields idNo (primary key & auto-increment), username, password, email.  I also have another table called profile with fields idNo, location, musicalInfluences, aboutMe etc.  All of these fields except idNo have the default value of "update."  What I want to be able to do is add a second insert statement to the user registration behaviour so that I can have the idNo number added to the profile tables as well as the registration table.  That way the registration and profile are linked by idNo and I can create a record-set do automatically populate the profile table on my profile page when the user logs in.  All of the different profile traits would say "update" and I can then use an update server behaviour for the user to update there profile.
    I might be approaching this the wrong way so I'm open to suggestions on how to create a user login and linked profile page.  One thing I could not work out was how, when the user clicks login with the correct credentials,  I was supposed to separate a first time user, directed to the create profile page, from a user who has already created a profile page and just wants to see it.  The only way I could think of was by using the default method explained before and then having an update page.  Sorry if that was a bit of a waffle.  Here is my code.  Any help would be much appreciated!!
    This is the script that I have included on my registration page.  I just extracted the php and used an include to keep the html page tidy.
    <?php require_once('Connections/soundstorm.php'); ?>
    <?php
    if (!function_exists("GetSQLValueString")) {
    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
      if (PHP_VERSION < 6) {
        $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
      $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
      switch ($theType) {
        case "text":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;   
        case "long":
        case "int":
          $theValue = ($theValue != "") ? intval($theValue) : "NULL";
          break;
        case "double":
          $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
          break;
        case "date":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;
        case "defined":
          $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
          break;
      return $theValue;
    // *** Redirect if username exists
    $MM_flag="MM_insert";
    if (isset($_POST[$MM_flag])) {
      $MM_dupKeyRedirect="usernameExists.php";
      $loginUsername = $_POST['username'];
      $LoginRS__query = sprintf("SELECT username FROM registration WHERE username=%s", GetSQLValueString($loginUsername, "text"));
      mysql_select_db($database_soundstorm, $soundstorm);
      $LoginRS=mysql_query($LoginRS__query, $soundstorm) or die(mysql_error());
      $loginFoundUser = mysql_num_rows($LoginRS);
      //if there is a row in the database, the username was found - can not add the requested username
      if($loginFoundUser){
        $MM_qsChar = "?";
        //append the username to the redirect page
        if (substr_count($MM_dupKeyRedirect,"?") >=1) $MM_qsChar = "&";
        $MM_dupKeyRedirect = $MM_dupKeyRedirect . $MM_qsChar ."requsername=".$loginUsername;
        header ("Location: $MM_dupKeyRedirect");
        exit;
    $editFormAction = $_SERVER['PHP_SELF'];
    if (isset($_SERVER['QUERY_STRING'])) {
      $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
    if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "registerForm")) {
      $insertSQL = sprintf("INSERT INTO registration (username, password, email) VALUES (%s, %s, %s)",
                           GetSQLValueString($_POST['username'], "text"),
                           GetSQLValueString($_POST['password'], "text"),
                           GetSQLValueString($_POST['email'], "text"));
      mysql_select_db($database_soundstorm, $soundstorm);
      $Result1 = mysql_query($insertSQL, $soundstorm) or die(mysql_error());
      $insertGoTo = "registerSuccess.html";
      if (isset($_SERVER['QUERY_STRING'])) {
        $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
        $insertGoTo .= $_SERVER['QUERY_STRING'];
      header(sprintf("Location: %s", $insertGoTo));
    ?>

    you can use a trigger in mysql. this trigger is for new records in your registration table. you can use mysql's last_insert_id() to get the last record inserted. just search for mysql triggers to get more info. note that this is not php code, it is mysql.

  • HELP! How te retrieve the last row in MYSQL database using Servlet!

    Hi ,
    I am new servlets. I am trying to retireve the last row id inserted using the servlet.
    Could someone show me a working sample code on how to retrieve the last record inserted?
    Thanks
    MY CODE
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class demo_gr extends HttpServlet {
    //***** Servlet access to data base
    public void doPost (HttpServletRequest req, HttpServletResponse resp)
         throws ServletException, IOException
         String url = "jdbc:mysql://sql2.njit.edu/ki3_proj";
              String param1 = req.getParameter("param1");
              PrintWriter out = resp.getWriter();
              resp.setContentType("text/html");
              String semail, sfname, slname, rfname, rlname, remail, message;
              int cardType;
              sfname = req.getParameter("sfname");
              slname = req.getParameter("slname");
              rfname = req.getParameter("rfname");
              rlname = req.getParameter("rlname");
              semail = req.getParameter("semail");
              remail = req.getParameter("remail");
              message = req.getParameter("message");
              //cardType = req.getParameter("cardType");
              cardType = Integer.parseInt(req.getParameter("cardType"));
              out.println(" param1 " + param1 + "\n");
         String query = "SELECT * FROM greeting_db "
    + "WHERE id =" + param1 + "";
              String query2 ="INSERT INTO greeting_db (sfname, slname ,semail , rfname , rlname , remail , message , cardType ,sentdate ,vieweddate) values('";
              query2 = query2 + sfname +"','"+ slname + "','"+ semail + "','"+ rfname + "','"+ rlname + "','"+ remail + "','"+ message + "','"+ cardType + "',NOW(),NOW())";
              //out.println(" query2 " + query2 + "\n");
              if (semail.equals("") || sfname.equals("") ||
              slname.equals("") || rfname.equals("") ||
              rlname.equals("") || remail.equals("") ||
              message.equals(""))
                        out.println("<h3> Please Click the back button and fill in <b>all</b> fields</h3>");
                        out.close();
                        return;
              String title = "Your Card Has Been Sent";
              out.println("<BODY>\n" +
    "<H1 ALIGN=CENTER>" + title + "</H1>\n" );
                   out.println("\n" +
    "\n" +
    " From  " + sfname + ", " + slname + "\n <br> To  "
                                            + rfname + ", " + rlname + "\n <br>Receiver Email  " + remail + "\n<br> Your Message "
                                            + message + "\n<br> <br> :");
                   if (cardType ==1)
                        out.println("<IMG SRC=/WEB-INF/images/bentley.jpg>");
                   else if(cardType ==2) {
                        out.println("<IMG SRC=/WEB-INF/images/Bugatti.jpg>");
                   else if(cardType ==3) {
                        out.println(" <IMG SRC=/WEB-INF/images/castle.jpg>");
    else if(cardType ==4) {
                        out.println(" <IMG SRC=/WEB-INF/images/motocross.jpg>");
    else if(cardType ==5) {
                        out.println(" <IMG SRC=/WEB-INF/images/Mustang.jpg>");
    else if(cardType ==6) {
                        out.println("<IMG SRC=/WEB-INF/images/Mustang.jpg>");
    out.println("</BODY></HTML>");
         try {
              Class.forName ("com.mysql.jdbc.Driver");
              Connection con = DriverManager.getConnection
              ( url, "*****", "******" );
    Statement stmt = con.createStatement ();
                   stmt.execute (query2);
                   //String query3 = "SELECT LAST_INSERT_ID()";
                   //ResultSet rs = stmt.executeQuery (query3);
                   //int questionID = rs.getInt(1);
                   System.out.println("Total rows:"+questionID);
    stmt.close();
    con.close();
    } // end try
    catch (SQLException ex) {
              //PrintWriter out = resp.getWriter();
         resp.setContentType("text/html");
              while (ex != null) { 
         out.println ("SQL Exception: " + ex.getMessage ());
         ex = ex.getNextException ();
    } // end while
    } // end catch SQLException
    catch (java.lang.Exception ex) {
         //PrintWriter out = resp.getWriter();
              resp.setContentType("text/html");     
              out.println ("Exception: " + ex.getMessage ());
    } // end doGet
    private void printResultSet ( HttpServletResponse resp, ResultSet rs )
    throws SQLException {
    try {
              PrintWriter out = resp.getWriter();
         out.println("<html>");
         out.println("<head><title>jbs jdbc/mysql servlet</title></head>");
         out.println("<body>");
         out.println("<center><font color=AA0000>");
         out.println("<table border='1'>");
         int numCols = rs.getMetaData().getColumnCount ();
    while ( rs.next() ) {
              out.println("<tr>");
         for (int i=1; i<=numCols; i++) {
    out.print("<td>" + rs.getString(i) + "</td>" );
    } // end for
    out.println("</tr>");
    } // end while
         out.println("</table>");
         out.println("</font></center>");
         out.println("</body>");
         out.println("</html>");
         out.close();
         } // end try
    catch ( IOException except) {
    } // end catch
    } // end returnHTML
    } // end jbsJDBCServlet

    I dont know what table names and fields you have but
    say you have a table called XYZ which has a primary
    key field called keyID.
    So in order to get the last row inserted, you could
    do something like
    Select *
    from XYZ
    where keyID = (Select MAX(keyID) from XYZ);
    Good Luckwhat gubloo said is correct ...But this is all in MS SQL Server I don't know the syntax and key words in MYSQL
    This works fine if the emp_id is incremental and of type integer
    Query:
    select      *
    from      employee e,  (select max(emp_id) as emp_id from employee) z
    where      e.emp_id = z.emp_id
    or
    select top 1 * from employee order by emp_id descUday

  • Algorithm help

    i have an issue trying to figure out the proper way to insert records into a database table. i apologize if this is more a database question than a java question but i didn't know where else to turn.
    my issue is trying to understand the best way to deal with autoincremented primary key fields used as row ids when you would need to use them for other detail and line tables. lets say it is a user table and i insert a user into it and its id is created off the autoincrementor...i proceed to want to add records to other tables and link them to this user i need to know what the id incremented to?
    so is the following algie correct:
    synchronize {
    insert record;
    get max(id) from table;
    thx, graeme.

    hmm, yes good point. i just read up on the mysql
    docs some functions that are connection specific so
    that can be sure the value retrieved won't be
    affected by other connections:If you set the isolation level properly and do things in a transaction you'll be fine.
    >
    i.e. last_insert_id(). thanks for the reply i'm
    going to look into these sequencers of oracle as well.Bad idea. This is MySQL-specific. The instance you use this function, your code isn't portable anymore. At least hide that implementation behind an interface if you must.
    It's SEQUENCE, not sequencers.
    %

  • How get Inserted value Id in MySql ?.

    Hi,
        How to Get Inserted value Id in MYSQL.
    I am using " select LAST_INSERT_ID() " But its not working Properly.Can u provide any other  solution For this.Please Help me.
    Thanks &  Regards
    Madhava Reddy.

    How to Get Inserted value Id in MYSQL.
    Hello,
    This is a forum for Transact-SQL = Microsooft SQL Server, not for MySQL; you should post your question to a more related forum.
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

  • JClient: after INSERT and COMMIT does not show the primary textfield value

    1. In my JClient master-detail form: When I insert a new record, enter data, and commit the changes... the master-panel's primarykey textfield is BLANK, when it should show the new auto-incremented number from the MySQL database. I have to close and open the form again to refresh that field again.
    2. In order to properly save new records in the detail-panel, I have to insert and save the above master-panel first. Is this the way JCLient handle master-detail forms?
    Thanks.

    Hi. Thanks for sharing your advice.
    Re my problem,
    if we have to refresh data by requery,i suggest you should use the way below:
    private JUNavigationBar navBar = new JUNavigationBar(true,false,true,false,true);
    navBar.setModel(JUNavigationBar.createPanelBinding(panelBinding, navBar));
    // after insert ,call this method
    navBar.doAction(navBar.BUTTON_EXECUTE);Tried this out but my textfield still won't get refreshed. Here is the code I came up with:
        private JUNavigationBar navBar = new JUNavigationBar() {
                public void doAction(int button) {
                    if (button == JUNavigationBar.BUTTON_INSERT) {
                        super.doAction(button);
                        navBar.doAction(navBar.BUTTON_EXECUTE);
                        return;
                    super.doAction(button);
            };Re your problem,
    I am developing application with JDev + MySQL,encounted another problem,
    how can i get the primary key supported by auto_increment column after insert?
    i constructed a vo whose sql statement is
    select last_insert_id() as last_id to get the value of auto_increment column.
    i found it can't get the right value unless commit the transaction.
    Would u please tell me your way?Based on what I experienced, we dont have to do the SELECT statement above. MySQL does auto-increment the primarykey but the JClient form just cant show it immediately, unless we close and re-open the form.
    What did I do to refresh the primarykey during insert? Please note that I got this solution accidentally coz I'm still a newbie in Java.
    A user want to add a record:
    1. He presses the Insert button.
    2. He enters data into a component (ex. textfield)
    3. The component's action-performed event is fired, and the following code is run:
            DCJboDataControl dc = (DCJboDataControl)panelBinding.getDataControl();
            ApplicationModule am = dc.getApplicationModule();
            Transaction tr = am.getTransaction();
            dc.commitTransaction();
            ViewObject vo = am.findViewObject("TblaccountsView1");
            vo.executeQuery();
            vo.last();It simply commits the transaction, goes to last (new) transaction, and lets the user continue his data encoding.
    Hope it helps and I hope theres an even better way to do this.

  • How to create 3 Classes from one

    Hello,
    I have one Databeseconnection class. But I would like creating 3 classes so that I have one connection class, one insert class and one select class.
    How Can I do It? Could you help me, please?
    package Test; import java.util.*; import java.sql.*; public class JavaDBTest { public static void main(String[] args){ Connection dbconn = null; Statement stmt=null; String mysqlHost = "localhost"; String mysqlDB = "dbname"; String mysqlUser = "root"; String mysqlPass = ""; int id=0; //open connection try { if(dbconn == null || dbconn.isClosed()) { // Load the JDBC driver. Class.forName("com.mysql.jdbc.Driver"); DriverManager.setLoginTimeout(10); // Establish the connection to the database. dbconn = DriverManager.getConnection("jdbc:mysql://" + mysqlHost + "/" + mysqlDB, mysqlUser, mysqlPass); stmt = dbconn.createStatement(); } } catch (Exception e) { System.out.println(e); } //Statements try { stmt.executeUpdate("INSERT INTO tabelename (RFID_Tagid,pub_type_id,Owner_id,Standort_id,user_id,year,actualyear,title,bibtex_id,report_type,survey,mark,series,volume,publisher,location,issn,isbn,firstpage,lastpage,journal,booktitle,number,institution,address,chapter,edition,howpublished,month,organization,school,note,abstract,url,doi,crossref,namekey,userfields,specialchars,cleanjournal,cleantitle,cleanauthor,read_access_level,edit_access_level,derived_read_access_level,derived_edit_access_level,pages,Signatur,roles_ids,entleihbarFuer,vormerkbarFuer,SichtbarFuer) VALUES (1,2,3,4,5,1998,2010,'ichbin titel','1','r',3,2,'s','volume','publis','location','issn','isbn','firstpage','lastpage','journal','booktitle','number','institution','address','chapter','edition','howpublished','month','organisation','school','note','abstract','url','doi','crossref','namekey','userfields',true,'cleanjournal','cleantitle','cleanautor',1,3,4,5,'pages','signatur','roles-ids','entleihbar','vorm','sichtb');"); ResultSet rs = stmt.executeQuery("SELECT LAST_INSERT_ID();"); rs.next(); id = rs.getInt(1); } catch (Exception e) { System.out.println(e); } System.out.println(id+""); try { ResultSet rs = stmt.executeQuery("SELECT * FROM tablename;"); while(rs.next()) { System.out.println(Integer.valueOf(rs.getString(1))); System.out.println(rs.getString(2)); System.out.println(rs.getString(3)); } } catch (Exception e) { System.out.println(e); } //close connection try { dbconn.close(); dbconn = null; } catch (Exception e) { System.out.println(e); } } }

    suneclipse wrote:
    Could you please write in java code?no doubt. So can anyone with a grain of common sense.
    That's not to say we're going to do your work for you.

  • Database toolkit - stored procedure doesn't work in labview

    Hello,
    I have written simple procedure that works good when I run it from workbench but doesn't work from labview. I want to insert some data and get primary key of inserted id:
    CREATE DEFINER=`root`@`localhost` PROCEDURE `new_procedure`(
    IN emp_id_val int,
    IN project_id_val int,
    IN work_mode_val int)
    BEGIN
    insert into work_managment.sessions (emp_id,project_id,work_mode)
    values (11,1,1);
    SELECT LAST_INSERT_ID();
    END
    and why that doesn't work when I call it from labview?
    when i replace last inserted id with:
    select max(session_id) as session from work_managment.sessions;
    it works good in labview
    What could be the problem??

    It could be that there is something screwy with LV, but given that it uses standard interfaces for comm with the DBMS, I would not expect that. A much more realistic possibility is that the toolkit is mucking things up. (A fairly common occurrence.)
    Try bypassing the toolbox -- which you don't really need anyway -- an talk directly to the ActiveX or .net interface.
    Also, what DBMS? What drivers are you using?
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • How can I use a mySQL database schema with numeric auto increment primary key instead of GUID?

    Hello!
    I'm using the TestStand "MySQL Insert (NI)" database schema with GUID as primary key. So everything works fine.
    But I prever using numeric values as primary key, because the database is in conjunction with another database which uses numeric values as primary key.
    Is this possible?
    Has anyone an idea how I can modify the "Generic Recordset (NI)" for use with MySQL?
    Thanks!
    Configuration:
    Microsoft Windows XP
    TestStand 3.1
    MySQL 4.1.12a
    MySQL ODBC 3.51 Driver
    Brosig

    Adam -
    The TestStand Database Logging feature does not allow you to run a separate SQL command after executing the command for a statement(table), so I do not think that you can use an auto incrementing column for the tables. There is just no way to get it back in a generic way. One option that I tried is something similar to the Oracle schema where you call a store procedure to return a sequence ID for each record that you want to add.
    So you would have to create the following sequence table in MySQL:
    CREATE TABLE sequence (id INT NOT NULL);
    INSERT INTO sequence VALUES (0);
    Then create a stored procedure as shown below that will increment the sequence value and return it in a recordset:
    CREATE PROCEDURE `getseqid`()
    BEGIN
            UPDATE sequence SET id=LAST_INSERT_ID(id+1);
            SELECT LAST_INSERT_ID();
    END
    Then update the MySQL tables to use INT primary and foreign key values, so the TestStand MySQL SQL file to create all tables would have text like this:
    CREATE TABLE UUT_RESULT
     ID    INT  PRIMARY KEY,
    ~
    CREATE TABLE STEP_RESULT
     ID    INT  PRIMARY KEY,
     UUT_RESULT   INT  NOT NULL,
    ~
    Then update the schema primary and foreign key columns in the TestStand Database Options dialog box to be INT to match the table. For the primary key columns, you will have to set the Primary Key Type to "Get Value from Recordset" and set the Primary Key Command Text to "call getseqid()". This will call the stored procedure to determine the next value to use as the ID value.
    Hope this helps...
    Scott Richardson
    National Instruments

  • Best Practice: Combine prepared statements with ;

    Hi,
    I would like to know what the best prctice is for combining prepared statements to give the query below
    INSERT INTO my_table (value) VALUES (?); SELECT LAST_INSERT_ID()The reason for this is that i have written a simple DB wrapper to handle my database connections and queries based on a property file containing sql strings. I would prefer not to change this wrapper code, but be able to specify combined queries in the sql string if possible.
    Thanks in advance

    Have you thought about using Batch statements ?

  • Javax.servlet.ServletException: Before start of result set

    I have a page where i want to put items that have been entered into a bean and put them into my SQL database. Firs of all i want to insert some value into my question table and then I use the SELECT LAST_INSERT_ID() function in mySQL to get the last incremented ID from the first statement. As you can see I then want to use this ID and insert it into the other statements to relate the tables but I get an exception which is shown below. The frist insert staemet works fine when the rest is commented out but when i try it with the other 2 insert statements it throws this back at me.
    javax.servlet.ServletException: Before start of result set
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:825)     org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:758)
    org.apache.jsp.authoring.question_005fmanager.process_005fquestion_jsp._jspService(process_005fquestion_jsp.java:453)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    java.sql.SQLException: Before start of result set
    com.mysql.jdbc.ResultSet.checkRowPos(ResultSet.java:4424)
    com.mysql.jdbc.ResultSet.getNativeInt(ResultSet.java:6210)
    com.mysql.jdbc.ResultSet.getInt(ResultSet.java:1335)     org.apache.jsp.authoring.question_005fmanager.process_005fquestion_jsp._jspService(process_005fquestion_jsp.java:126)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)     org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    My code is shown here
    // gets the feedback string parameters
    if (request.getParameterValues("feedbackBox") != null) {
        String [] feedbackList = request.getParameterValues("feedbackBox");
        questionData.feedback = feedbackList;
    //gets the session username variable
    String insertQuestion1__username = null;
    if (session.getValue("MM_Username") != null) {
        insertQuestion1__username = (String)session.getValue("MM_Username");
    //Creates a new mySQL date
    java.sql.Date currentDate = new java.sql.Date((new java.util.Date()).getTime());
    //goes thorugh each element of the scores array and calculates maxScore 
    questionData.maxScore = 0;
    for (int i = 0; i < questionData.scores.length; i++) {
        questionData.maxScore = questionData.maxScore + questionData.scores;
    Driver DriverinsertQuestion = (Driver)Class.forName(MM_connQuestion_DRIVER).newInstance();
    Connection ConninsertQuestion1 = DriverManager.getConnection(MM_connQuestion_STRING, MM_connQuestion_USERNAME,
    MM_connQuestion_PASSWORD);
    questionData.numOutcomes = questionData.choices.length;
    PreparedStatement insertQuestion1 =
    ConninsertQuestion1.prepareStatement("INSERT INTO Question.question (Topic_ID, Description, Image, Author, Created_Date, Max_Score, Question_Type) VALUES ('"
    + questionData.topicID + "', '"
    + questionData.questionText + "', '"
    + questionData.questionImage + "', '"
    + insertQuestion1__username + "', '" + currentDate
    + "', " + questionData.maxScore + ", '"
    + questionData.questionType + "') ");
    insertQuestion1.executeUpdate();
    PreparedStatement StatementlastID = ConninsertQuestion1.prepareStatement("SELECT LAST_INSERT_ID()");
    ResultSet lastID = StatementlastID.executeQuery();
    int questionID = lastID.getInt(1);
    Driver DriverinsertQuestion2 = (Driver)Class.forName(MM_connAnswer_DRIVER).newInstance();
    Connection ConninsertQuestion2 = DriverManager.getConnection(MM_connAnswer_STRING, MM_connAnswer_USERNAME,
    MM_connAnswer_PASSWORD);
    PreparedStatement insertQuestion2 =
    ConninsertQuestion2.prepareStatement("INSERT INTO Answer.question (Question_ID, Question_Description, Question_Type, Topic, Number_Outcomes, Question_Wording) VALUES ('"
    + questionID + "', '" + questionData.questionLabel
    + "', '" + questionData.questionType + "', '"
    + questionData.questionType + "', '"
    + questionData.topicID + "', '"
    + questionData.numOutcomes + "', '"
    + questionData.questionText + "' ) ");
    insertQuestion2.executeUpdate();
    Driver DriverinsertOutcomes = (Driver)Class.forName(MM_connAnswer_DRIVER).newInstance();
    Connection ConninsertOutcomes = DriverManager.getConnection(MM_connAnswer_STRING, MM_connAnswer_USERNAME,
    MM_connAnswer_PASSWORD);
    for (int i = 0; i < questionData.numOutcomes; i++) {
    PreparedStatement insertOutcomes =
    ConninsertOutcomes.prepareStatement("INSERT INTO Answer.outcome (Question_ID, Outcome_Number, Outcome_Text, Score, Feedback) VALUES ( '"
    + questionID + "', '" + i + "', '"
    + questionData.choices[i] + "', '"
    + questionData.scores[i] + "', '"
    + questionData.feedback[i] + "' ) ");
    insertOutcomes.executeUpdate();

    further to Limo2kz's problem, LAST_INSERT_ID() will return 0 if the last INSERT statement actually has inserted 0 records. this could happen if the previous INSERT attempt has failed.
    as far as i can remember, you should find out if the account or user that you are currently using to connect to MySQL database is allowed to do more SQL executions and create more SQL connections at certain given time (i.e., 10 executions in 1 hour, 10 connections in 1 hour). otherwise, you would have subsequent SQL exceptions because the database server won't allow you to execute them, thus giving you a null ResultSet.

  • Once again:  Does MySQL allow multiple querys in one database transaction???

    Hello to ALL!!!
    The problem is:
    I'm trying to make simple query (database: "myDB" (engine:
    myisam/innodb - doesn't mater) with one table: "Info" with two
    columns: "Id" (autoinc), "info_c" (varchar):
    <cfif structkeyexists (form, "name")>
    <cfquery datasource="myDB" name="qDB" >
    INSERT into Info (info_c)
    VALUES ('#form.name#');
    SELECT @@identity AS Id
    </cfquery>
    </cfif>
    <cfform>
    <cfinput type="text" name="name">
    <cfinput type="submit" name="submit">
    </cfform>
    BUT after "Submit" I get:
    Error Executing Database Query.
    You have an error in your SQL syntax; check the manual that
    corresponds to your MySQL server version for the right syntax to
    use near '; select @@identity as Id' at line 2
    Please, tell me WHY???
    I have:
    MySQL
    Server information:
    MySQL version: MySQL 5.1.25-rc-community via TCP/IP
    Clent Information:
    Version: MySQL client version 5.1.11
    Coldfusion Version Information:
    Version 8,0,0,176276
    Great THANKS for your answers!!!

    > SELECT @@identity AS Id
    AFAIK, MySQL uses LAST_INSERT_ID(). @@IDENTITY is MS SQL
    specific. Though SCOPE_IDENITY() is recommended over @@IDENTITY.
    What version of CF are you using? ColdFusion supports the
    "result" attribute, which will return the ID value for simple
    inserts. See the documentation for details
    http://livedocs.adobe.com/coldfusion/8/Tags_p-q_17.html
    > Do JDBC drivers for MySQL prohibit the use of multiple
    queries
    > in a single database transaction???
    For security purposes this is disabled by default. To enable
    it you must modify your datasource url
    http://www.petefreitag.com/item/357.cfm

  • Possible thread issue?

    I'v now come across a code problem that I simply cannot understand what is happending here.
    The code is part of a cfc module that is behind a web-service.
    The problem here is the transID.
    When you start putting a bit of load on this code, the transID gets mangled/confused/....
    When looking at the first cflog here, the trans id is the correct value is an thedatabase table.
    However, after the values are assigned to stTrans, the trans id is different! It is that of another tx that happend later on...
    Nowere is the transID updated in the code between the two cflog's. The value in the cflog is correct, as it is this value that I receive on the other side of the WebService module....
    Here is the logfile output
    Look for card no xxxx00213
    Information","jrpp-5","12/07/09","20:11:27","GCCSVPWS","Process tx for xxxxxxx00213 with tx id 163537 and Thread.txid is 163537"
    "Information","jrpp-0","12/07/09","20:11:27","GCCSVPWS"," Process tx (after transaction) for xxxxx000346 with tx id 163537 and Thread.txid is 163537"
    "Information","jrpp-4","12/07/09","20:11:27","GCCSVPWS"," Process tx (after transaction) for xxxx38304 with tx id 163537 and Thread.txid is 163537"
    "Information","jrpp-7","12/07/09","20:11:27","GCCSVPWS","Process tx for xxxxxxxx254"
    "Information","jrpp-9","12/07/09","20:11:27","GCCSVPWS","Process tx for xxxxxxx0270"
    "Information","jrpp-16","12/07/09","20:11:27","GCCSVPWS"," Process tx (after transaction) for xxxxxx005097 with tx id 163537 and Thread.txid is 163537"
    "Information","jrpp-18","12/07/09","20:11:27","GCCSVPWS"," Process tx (after transaction) for xxxxxx00239 with tx id 163537 and Thread.txid is 163537"
    "Information","jrpp-19","12/07/09","20:11:27","GCCSVPWS"," Process tx (after transaction) for xxxxxx00304 with tx id 163537 and Thread.txid is 163537"
    "Information","jrpp-8","12/07/09","20:11:27","GCCSVPWS","Process tx for xxxxxxxxx12 with tx id 163538 and Thread.txid is 163538"
    "Information","jrpp-9","12/07/09","20:11:27","GCCSVPWS","Process tx for xxxxxxxxx270 with tx id 163539 and Thread.txid is 163539"
    "Information","jrpp-3","12/07/09","20:11:27","GCCSVPWS"," Process tx (after transaction) for xxxxxxxx0288 with tx id 163539 and Thread.txid is 163539"
    "Information","jrpp-7","12/07/09","20:11:27","GCCSVPWS","Process tx for xxxxxxxxxxx254 with tx id 163540 and Thread.txid is 163540"
    "Information","jrpp-5","12/07/09","20:11:27","GCCSVPWS"," Process tx (after transaction) for xxxxxxxxxx0213 with tx id 163540 and Thread.txid is 163540"
    I found a problem when I did code optimizationon the other side of the webservice. First thought it was the web service, but trace it right down to this bit of code on the one server.
    This is happening on my Mac's VM's running CentOS 5.2 and Coldfusion 8 on top of that.....
    Coldfusion details:
    Server Product
    ColdFusion
    Version
    8,0,1,195765 
    Operating System
    UNIX 
    OS Version
    2.6.18-128.2.1.el5 
    JVM Details
    Java Version
    1.6.0_04 
    Database is MySQL version 5.0
    Any any any  ideas will be appreciated!
    snipped ----
                        SELECT last_insert_id() AS transid;
                    </cfquery>
                    <cfset theTransID = trans_insert.transid>
                    <cfset Thread.txid = trans_insert.transid>
                    <cflog file="transdao_cfc" text="Process tx for #cardnumber# with tx id #theTransID# and Thread.txid is #Thread.txid#" type="information">
                    <!--- Update acct balance on gateway --->
                    <cfquery datasource="#variables.dsn#">
                        UPDATE acct_balances
                        SET
                            acct_balance = acct_balance + #arguments.amount#,
                            acct_balance_available = acct_balance_available + #arguments.amount#
                        WHERE
                            acct_id = <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#arguments.acctid#">
                    </cfquery>
               </cftransaction>
                <!---------------------------------------------------------------------------
                CHECK FOR NEG to POS
                ---------------------------------------------------------------------------->
                <cftry>
                    <cfif theCurrentActualBalance LT 0 AND theNewActualBalance GTE 0>
                        <cfquery datasource="#variables.dsn#">
                            UPDATE fees_collection
                            SET
                                settled = <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="1">,
                                settled_trans_id = <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#theTransID#">,
                                settled_dttm = NOW()
                            WHERE
                                acct_id = <cfqueryparam cfsqltype="CF_SQL_INTEGER" value="#arguments.acctid#"> AND
                                settled = 0
                        </cfquery>
                    </cfif>
                    <cfcatch type="any"><cflog file="transdao_cfc" text="#cfcatch.toString()#"></cfcatch>
                </cftry>
                <!--- Set response --->
                <cfset stTrans.responsecode = 00 />
                <cfset stTrans.transid = theTransID />
                <cfset stTrans.success = true />
                <cfset stTrans.message = "" />
                <cfset stTrans.start_actualbalance = theCurrentActualBalance>
                <cfset stTrans.start_availablebalance = theCurrentAvailableBalance>
                <cfset stTrans.end_actualbalance = theNewActualBalance>
                <cfset stTrans.end_availablebalance = theNewAvailableBalance>
                <cflog file="transdao_cfc" text=" Process tx (after transaction) for #cardnumber# with tx id #stTrans.transid# and Thread.txid is #Thread.txid#" type="information">

    I update the text fields in the following method :
    public void performSummaryCalculation() {
             CalcSheetTotals_IF calcSheetTotals = (CalcSheetTotals)CalcSheetTotalsGUITableModel.rowTotalsData[5];
             Double quotedPrice = calcSheetTotals.getQuotedPrice();
             log("quoted price to string = " + quotedPrice.toString());
             textField_calcSheetOriginalAmountOfClaim.setText("R " + quotedPrice.toString());
                //panel_calcSheetSummary.repaint();
             //textField_calcSheetOriginalAmountOfClaim.updateUI();
             //panel_calcSheetSummary.updateUI();
              textField_calcSheetOriginalAmountOfClaim.repaint();
        }

Maybe you are looking for

  • Measures/Time Calculation

    I created calculations in the outline which when finished, gives me the final correct result set, but this result set is spead over multiple time periods.TIMEAVGCON2=@AVG(FEB,MAR,APR)-Calc(This calculates over all measures when I really only what it

  • Does the serial number stay the same for CS6 downloads on seperate computers?

    I am going to download my CS6 onto a second computer (redeem by second download) and I was just curious if my serial number will be the same since its the same product or if I need to redeem another one. How do I go about doing that?

  • Panther Updates for a Mac without internet?

    Okay, I'm trying to collect all of the updates I'll need for a Mac I'm going to set up running 10.3.9... Add to my list that I've made so far.. -Mac OS 10.3.9 Update -Security Update 2007-008 -iTunes 7.7.1 -QuickTime 7.5 -Safari 1.3.1 -Safari 1.3.2 -

  • Probleme mit Wifi

    Hallo zusammen, ich habe das Yoga 2 13 mit Win 8.1 und folgendes Problem. Immer wieder schaltet sich das Wifi ab und kann schlußendlich nur mehr vom Administrator eingeschalten werden. Das ist aber bei uns nicht praktikabel. Das muss auf jeden Fall d

  • Showing recent changes to a few pages

    I have two sections in our company's Sharepoint site - one is Exchange Server Help Documents and the other is How-To Articles for staff.  I'm trying to make a content rollup on the overall IT page to show what's changed recently, but am having no luc