To handle exception in insert query

Hi ,
I am trying it insert certain records from another table A to temp table B, while doing insert i am having exception of unique constraint in table B how can i check which record is throwing exception while inserting in table A
for eg:
insert into A
select * from B;
i need to handle exception in which record of B i am getting unique constraint error

Hi,
If you add an error logging clause (with keywords LOG ERRORS), then you can insert a row into another table for each row that can't be inserted according to your INSERT statement.
To query table A to see which ids already exist in table B, you can say
SELECT  *
FROM    a
WHERE   a_id  IN (
                      SELECT  b_id
                      FROM    b
where b.b_id is the unique key in table b, and a.a_id is the value you're truing to insert into that column.
If you just want to skip the insert when a matching row already exists, then use MERGE instead of INSERT.

Similar Messages

  • Handling EXCEPTION in SQL query itself

    Hi friends,
    I have situation like the following:
    SELECT CASE WHEN ('1') > 0 THEN 'Y'
    ELSE 'N'
    END
    FROM dual;
    For this query, Oracle returns 'Y'. That's OK. Somtimes instead of '1' some string may come ('1a' or 'gf'). In such cases Oracle returns 'invalid number' exception. As per my requirement, in such cases, 'N' should be returned.
    Is it possible to perform this in SQL (without going to PLSQL)?
    Thanks in advance.

    "case-when" statements are evaluated in order.
    so you must do something like this:
    SELECT
    CASE WHEN <is not number>THEN 'N'
    CASE WHEN <is greater than 0>THEN 'Y'
    Now "<is greater than 0>" will always have number for input, can't get "not number" error there.
    See this thread:
    Re: regular expression: integer is between N..M
    Edited by: CharlesRoos on May 27, 2010 5:03 AM

  • Can we handle exceptions for the expressions in select query?

    Hi all,
    Can we handle exceptions for the expressions in select query.
    I created a view, there I am extracting a substring from a character data and expected that as a number.
    For example consider the following query.
    SQL> select to_number( substr('r01',2,2) ) from dual;
    TO_NUMBER(SUBSTR('R01',2,2))
    1
    Here we got the value as "1".
    Consider the following query.
    SQL> select to_number( substr('rr1',2,2) ) from dual;
    select to_number( substr('rr1',2,2) ) from dual
    ORA-01722: invalid number
    For this I got error. Because the substr returns "r1" which is expected to be as number. So it returns "Invalid number".
    So, without using procedures or functions can we handle these type of exceptions?
    I am using Oracle 10 G.
    Thanks in advance.
    Thank you,
    Regards,
    Gowtham Sen.

    SQL> select decode(ltrim(rtrim(translate(substr('r21', 2, 2), '0123456789', ' ' ), ' '), ' '), null, (substr('r21', 2, 2)), null) from dual;
    DE
    21
    SQL> ed a
    SQL> select decode(ltrim(rtrim(translate(substr('rr1', 2, 2), '0123456789', ' ' ), ' '), ' '), null, (substr('rr1', 2, 2)), null) from dual;
    D
    -

  • Exception handling in  in insert statemnt

    i am inserting values in to a table in a procedure.for insert statemnt what are the possible exceptions that may occur.
    how to handle exceptions for that insert statement(other than when others)

    user639995 wrote:
    is there any possiblity to use if sql%rowcount = 0 then
    RAISE e1;
    like thisNot for an insert statement, no.
    sql%rowcount returns the number of rows effected by a DML statement.
    For any of the statements you can only check sql%rowcount after the DML statement successfully executes, and it will only return a 0 if no rows were effected by that DML statement e.g. if an update effected no rows or an insert ... select ... actually inserted no rows etc.
    If an exception occurs during a DML statement then execution will pass directly to the exception handler so you won't have the opportunity to test for sql%rowcount after the statement.
    You should have an exception handler for expected exceptions.
    If an exception is not expected then you should let your code raise it up so it is seen and not handled.
    example of defining exceptions for non-named error numbers...
    SQL> create table x (x number);
    Table created.
    SQL> insert into x values ('x');
    insert into x values ('x')
    ERROR at line 1:
    ORA-01722: invalid number
    SQL> set serverout on
    SQL> declare
      2    ex_not_number exception;
      3    pragma exception_init(ex_not_number, -1722);
      4  begin
      5    insert into x values (1);
      6    commit;
      7    insert into x values ('A');
      8    commit;
      9  exception
    10    when ex_not_number then
    11      dbms_output.put_line('An attempt to insert a value that is not a number was made.');
    12  end;
    13  /
    An attempt to insert a value that is not a number was made.
    PL/SQL procedure successfully completed.
    SQL> select * from x;
             X
             1
    SQL>Further details on exception handling here:
    [PL/SQL 101 : Exception Handling|http://forums.oracle.com/forums/thread.jspa?threadID=697262&tstart=50]

  • How to handle exceptions of rfc in web dydnpro

    hi all,
    i want to handle exceptions of Remote function module in webdynpro.how can we do that one.are there any variables in model class for those exceptions.
    regards
    Naidu

    Hi,
    Hope the following snippet answers ur query
    IWDMessageManager manager = wdComponentAPI.getMessageManager();
                   try{
                        wdContext.currentB_Quotation_Createfromdata_InpElement().modelObject().execute();
                        wdContext.nodeOutputQuotation().invalidate();
                   } catch(WDDynamicRFCExecuteException ce) {
                        manager.reportException(ce.getMessage(), false);

  • Insert query into workbook

    Hi experts,
    when i try to insert query into a workbook i get the following error message
    <internal error> Receiving from the BW server failed BW server raised exception: SYSTEM_FAILURE Do you want to see more information?
    when i click yes i get
    No roll storage space of length 3600 available for OCCURS area.
    Further the error reads
    Error Gruop
    RFC_ERROR_SYSTEM_FAILURE
    Message
    No roll storage space of length 3600 available for OCCURS area.
    I would appreciate if someone could give me a quick way to reslove this issue..
    Thnaks
    DAVE

    Thanks Abdul,
    May i know why this error occurs??
    thanks
    Dave

  • Preventing column to be in insert query when value is null

    I'm running DB and have a column defined as GENERATED ALWAYS.
    What this means is that I can't use insert into table(col) values (null) because DB2 does not want the column to be part of the insert query at all.
    Is there a way to prevent toplink from generating the column when its null?

    Hi jsutherl,
    If I set setIsReadOnly(true) in my session customzier and specify insertable and updateable as false, I get the followine error:
    Exception [TOPLINK-46] (Oracle TopLink Essentials - 2.0.1 (Build b04-fcs (04/11/2008))): oracle.toplink.essentials.exceptions.DescriptorException
    Exception Description: There should be one non-read-only mapping defined for the primary key field [TBL.PERSON.ID].
    Descriptor: RelationalDescriptor(com.x.entity.Person--> [DatabaseTable(TBL.PERSON)])
    I'm guessing this is because ID is a primary key and its forcing me to have a non-read-only mapping.
    But the dillemma is that if I specify a non-read-only mapping than any insert on the table results in Toplink inserting the Java type null for the column which results in the following exception:
    Internal Exception: com.ibm.db2.jcc.b.SQLException: A value cannot be specified for column "ID" which is defined as GENERATED ALWAYS.
    This is because the field is defined as an IDENTITY in DB2.
    Any thoughts?

  • Maximum length of identifier in insert query

    Hi,
    I am using Sybase 12.0 with JConnect 5.
    I am facing some problem with insert query.
    It gives exception like " identitifer is too long maximum length is 30"
    If i run then same query on winSql its working fine but with JDBC not working.
    Pls help me reagrding this.

    Hi,
    this is the error message i am getting
    com.sybase.jdbc2.jdbc.SybSQLException: The identifier that starts with '"T3211PU,,insert into Illustr' is too long. Maximum length is 28.
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.sybase.jdbc2.tds.Tds.processEed(Tds.java:2408)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.sybase.jdbc2.tds.Tds.nextResult(Tds.java(Compiled Code))
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.sybase.jdbc2.jdbc.ResultGetter.nextResult(ResultGetter.java:69)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.sybase.jdbc2.jdbc.SybStatement.nextResult(SybStatement.java:201)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.sybase.jdbc2.jdbc.SybStatement.nextResult(SybStatement.java:182)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.sybase.jdbc2.jdbc.SybStatement.executeLoop(SybStatement.java:1535)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.sybase.jdbc2.jdbc.SybStatement.execute(SybStatement.java:1527)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.sybase.jdbc2.jdbc.SybStatement.execute(SybStatement.java:742)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.dcx.catl.macscompiler.util.CommonDataAccessManager.execQueryRetState(CommonDataAccessManager.java:759)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.dcx.catl.macscompiler.bo.RemoveIllustrationJavaBean.execute(RemoveIllustrationJavaBean.java:414)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.dcx.catl.macscompiler.ao.RemoveIllustrationAction.execute(RemoveIllustrationAction.java:219)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:446)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:266)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1292)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:510)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.ibm.ws.webcontainer.servlet.IdleServletState.service(StrictLifecycleServlet.java:313)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:948)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:530)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:176)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.ibm.ws.webcontainer.srt.WebAppInvoker.doForward(WebAppInvoker.java:79)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.ibm.ws.webcontainer.srt.WebAppInvoker.handleInvocationHook(WebAppInvoker.java:201)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.ibm.ws.webcontainer.cache.invocation.CachedInvocation.handleInvocation(CachedInvocation.java:71)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R      at com.ibm.ws.webcontainer.srp.ServletRequestProcessor.dispatchByURI(ServletRequestProcessor.java:182)
    [4/27/05 17:02:50:031 IST] 575ee900 SystemErr R [4/27/05 17:02:50:031 IST] 575ee900 SystemOut O SQLException: The identifier that starts with '"T3211PU,,insert into Illustr' is too long. Maximum length is 28.

  • Syntax error in insert query

    I have a flash form that is used to inserts a record into an
    Access database table. In the for there are 4 datefields, several
    text input fields, and several select fields. When I submit the
    form, I get a syntax error that reads:
    Executing Database Query. [Macromedia][SequeLink JDBC
    Driver][ODBC Socket][Microsoft][ODBC Microsoft Access Driver]
    Syntax error in INSERT INTO statement.
    The error occurred on line 184. Complex object types cannot
    be converted to simple values.
    Line 184 is the last line of the Values in the insert query.
    The query looks like this:
    <CFQUERY DATASOURCE="#REQUEST.DataSource#">
    INSERT INTO EstimateNumber(
    BidNumber,
    Project,
    JobSite,
    EstimatedBy,
    Region,
    Company,
    Division,
    InquiryNumber,
    SafetyChecklist,
    SafetyChecklistDate,
    QCChecklist,
    QCChecklistDate,
    EstimatedValue,
    UserUsername,
    UserPassword,
    Updated,
    ReviewDate,
    ReviewedBy,
    Discipline,
    BidDate,
    JobNumber,
    UpdatedBy
    VALUES(
    #FORM.BidNumber#,
    '#FORM.Project#',
    '#FORM.JobSite#',
    '#FORM.EstimatedBy#',
    #FORM.Region#,
    #FORM.Company#,
    #FORM.Division#,
    '#FORM.InquiryNumber#',
    #FORM.SafetyChecklist#,
    #FORM.SafetyChecklistDate#,
    #FORM.QCChecklist#,
    '#FORM.QCChecklistDate#',
    #FORM.EstimatedValue#,
    '#FORM.UserUsername#',
    '#FORM.UserPassword#',
    #FORM.Updated#,
    #FORM.ReviewDate#,
    #FORM.ReviewedBy#,
    #FORM.Discipline#,
    #FORM.BidDate#,
    #FORM.JobNumber#,
    '#FORM.UpdatedBy#'
    </CFQUERY>
    Any recomendations?

    Date/Time in Access provide some pretty strage hurdles. In
    many occassions I have simply changed the field to a Text field and
    ran with that and never seemed to have problems with the result. I
    didn't like doing it but I never received errors. I have been
    receiving some parameter errors with <cfqueryparam> like the
    database doesn't recognized the preceding declared field in the
    update or insert query. Here is an example of a wierd error with
    Access. I have 2 tables. One is for estimate numbers and the other
    is for sub estimate numbers that can be assigned to specific
    estimate numbers. If is actually a complicated explanation about
    what is taking place behind the doors on this. The concept is
    simple on the surface. Both tables have the same fields except the
    subestimate table has 1 extra for a user defined subestimate
    number. The only relation between the two will be the estimate
    number. This insert works fine.
    INSERT INTO EstimateNumber(
    BidNumber,
    Project,
    JobSite,
    EstimatedBy,
    Region,
    Company,
    Division,
    InquiryNumber,
    SafetyChecklist,
    SafetyChecklistDate,
    QCChecklist,
    QCChecklistDate,
    EstimatedValue,
    UserUsername,
    UserPassword,
    ReviewDate,
    Discipline,
    BidDate,
    JobNumber,
    UpdatedBy
    VALUES(
    #FORM.BidNumber#,
    '#FORM.Project#',
    '#FORM.JobSite#',
    '#FORM.EstimatedBy#',
    #FORM.Region#,
    #FORM.Company#,
    #FORM.Division#,
    '#FORM.InquiryNumber#',
    #FORM.SafetyChecklist#,
    <cfqueryparam
    value="#FORM.SafetyChecklistDate#"
    cfsqltype="CF_SQL_DATE "
    maxlength="50"
    >,
    #FORM.QCChecklist#,
    <cfqueryparam
    value="#FORM.QCChecklistDate#"
    cfsqltype="CF_SQL_DATE "
    maxlength="50"
    >,
    #FORM.EstimatedValue#,
    '#FORM.UserUsername#',
    '#FORM.UserPassword#',
    <cfqueryparam
    value="#FORM.ReviewDate#"
    cfsqltype="CF_SQL_DATE "
    maxlength="50"
    >,
    #FORM.Discipline#,
    <cfqueryparam
    value="#FORM.BidDate#"
    cfsqltype="CF_SQL_DATE "
    maxlength="50"
    >,
    #FORM.JobNumber#,
    '#FORM.UpdatedBy#'
    This next one is the same exact query with the same table
    setup with one added field but kicks back a parmeter error
    expecting 4. I can't explain it.
    INSERT INTO SubEstimate(SubBidNumber,
    BidNumber,
    Project,
    JobSite,
    EstimatedBy,
    Region,
    Company,
    Division,
    InquiryNumber,
    SafetyChecklist,
    SafetyChecklistDate,
    QCChecklist,
    QCChecklistDate,
    EstimatedValue,
    UserUsername,
    UserPassword,
    ReviewDate,
    Discipline,
    BidDate,
    JobNumber,
    UpdatedBy
    VALUES(#FORM.SubBidNumber#,
    #FORM.BidNumber#,
    '#FORM.Project#',
    '#FORM.JobSite#',
    '#FORM.EstimatedBy#',
    #FORM.Region#,
    #FORM.Company#,
    #FORM.Division#,
    '#FORM.InquiryNumber#',
    #FORM.SafetyChecklist#,
    <cfqueryparam
    value="#FORM.SafetyChecklistDate#"
    cfsqltype="CF_SQL_DATE "
    maxlength="50"
    >,
    #FORM.QCChecklist#,
    <cfqueryparam
    value="#FORM.QCChecklistDate#"
    cfsqltype="CF_SQL_DATE "
    maxlength="50"
    >,
    #FORM.EstimatedValue#,
    '#FORM.UserUsername#',
    '#FORM.UserPassword#',
    <cfqueryparam
    value="#FORM.ReviewDate#"
    cfsqltype="CF_SQL_DATE "
    maxlength="50"
    >,
    #FORM.Discipline#,
    <cfqueryparam
    value="#FORM.BidDate#"
    cfsqltype="CF_SQL_DATE "
    maxlength="50"
    >,
    #FORM.JobNumber#,
    '#FORM.UpdatedBy#'
    IF I get rid of the cfqueryparam fields it works. If I simply
    remove the param, I get a Syntax error. Needless to say I commented
    this query for the sake of sanity for the time being.

  • Not handled exception due to uninitialized variables ?

    I have successfully added a sap-proxy to my
    application.
    But when I try to invoke e.g. Bapi_Customer_Getdetail
    using concrete parameters,
    there's an error message indicating:
    <i>A non handled exception of type 'SAP.Connector.RFcException'.. has occured;
    further information:
    max.length for value / ID exceeded .. (some strange signs)</i>
    But I've in deed assigned values to my parameters, which
    are mandatory input parameters for SAP.
    Can anyone tell me, what I'm doing wrong.
    Thank you
    j.kerscher

    So what does it mean in below quotation from "PL/SQL User's Guide and Reference", that host environment determines what is rolled back, if the database manages it, as you have written?
    How Oracle Does Implicit Rollbacks
    +"Before executing an INSERT, UPDATE, or DELETE statement, Oracle marks an implicit savepoint (unavailable to you). If the statement fails, Oracle rolls back to the savepoint. Normally, just the failed SQL statement is rolled back, not the whole transaction. However, *if the statement raises an unhandled exception, the host environment determines what is rolled back*.+
    Edited by: twrzodak on Sep 23, 2008 8:56 AM

  • Performance issues with respect scheme registration,select & insert query

    I am facing performance issues with respect to schema registration,Select & insert query towards 10.2.0.3 version.It is taking around 45 minutes to register schema and it is taking around 5 min to insert a single document into xml db where as it was taking less than min to insert a single document into xml db of 9.2.0.6 version.Would like to know the issue and solution to resolve this issue.Please help me out on this as it is very urgent for me

    Since it appears that this is an XML DB specific question, you're probably better off posting in the XML DB. The folks over there have much more experience with the ins and outs of that particular product.
    Justin

  • Invalid Handle Exception-What is the reason?

    I face with "Invalid Handle exception" (SQLException) while using the following code.
    Could anybody tell me the possible reasons/Situation the error rise?
    stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(SQLStmt);
         if(rs!=null){
    ResultSetMetaData rsm = rs.getMetaData();
         int totalcols = rsm.getColumnCount();
         Vector temp;
         while (rs.next()) {
         Vector temp = new Vector();
         for (int i = 1; i <= totalcols; i++) {
              String value = rs.getString(i);
              if (value == null) {
              value = "";
         temp.addElement(value);
         }//for loop ends here
         valueVector.addElement(temp);
         rs.close();
         stmt.close();     
    Thank you all

    Vector temp;
    while (rs.next()) {
    Vector temp = new Vector();Are you sure that this is the code you are running? The reason I ask is that I'm pretty sure that it won't compile, at least under JDK1.4. You should get a compile error something like "temp is already defined".
    If thats not the problem you need to find out on which line the error actually occurs. You can get this from the exception by calling the printStackTrace() method.
    Col

  • How can I insert Query in a Workbook

    Hi,
    I am new in BI 7.0. I am trying to insert a query in a workbook. but the tools button is not giving me the option to insert query like 3.X
    How can i insert query in 7.0
    Can anybody please give me the step by step instruction.
    Thanks in Advance

    1. Open BEx ANalyzer.
    2. Create new excel workbook by hitting the "New" icon in Excel.
    3. Logon to a backend BI system.
    4. Click the design mode icon.
    5. Put your mouse on a cell and insert a table.
    6. Assign a dataprovider to this table.
    7. Switch off design mode.
    Hope it Helps
    Chetan
    @CP..

  • How can I enter the data from the recordset into your insert query

    Hi
    i would like to know how I can enter the data from the recordset into your insert query without using a  hidden field.
    thanks
    ------------------------------------------------------------------------------------Below is the code------------------------------------------------------------------------------------- -----
    <?php require_once('../../Connections/ezzyConn.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;
    $editFormAction = $_SERVER['PHP_SELF'];
    if (isset($_SERVER['QUERY_STRING'])) {
      $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
    if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "frmpostComment")) {
       $insertSQL = sprintf("INSERT INTO comments (com_topic, com_user, title,  com_content, com_date, online_id) VALUES (%s, %s, %s, %s, %s, %s)",
                           GetSQLValueString($_POST['com_topic'], "int"),
                           GetSQLValueString($_POST['commentby'], "int"),
                           GetSQLValueString($_POST['title'], "text"),
                           GetSQLValueString($_POST['com_content'], "text"),
                           GetSQLValueString($_POST['com_date'], "text"),
                           GetSQLValueString($_POST['online_id'], "int"));
      mysql_select_db($database_ezzyConn, $ezzyConn);
      $Result1 = mysql_query($insertSQL, $ezzyConn) or die(mysql_error());
      $insertGoTo = "index.php";
      if (isset($_SERVER['QUERY_STRING'])) {
        $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
        $insertGoTo .= $_SERVER['QUERY_STRING'];
      header(sprintf("Location: %s", $insertGoTo));
    $colname_rsCommentby = "-1";
    if (isset($_SESSION['MM_Username'])) {
      $colname_rsCommentby = $_SESSION['MM_Username'];
    mysql_select_db($database_ezzyConn, $ezzyConn);
    $query_rsTopics = "SELECT topic_id, topic FROM topics ORDER BY topic_date DESC";
    $rsTopics = mysql_query($query_rsTopics, $ezzyConn) or die(mysql_error());
    $row_rsTopics = mysql_fetch_assoc($rsTopics);
    $totalRows_rsTopics = mysql_num_rows($rsTopics);
    mysql_select_db($database_ezzyConn, $ezzyConn);
    $query_rsOnline = "SELECT online_id, `online` FROM `online` ORDER BY online_id DESC";
    $rsOnline = mysql_query($query_rsOnline, $ezzyConn) or die(mysql_error());
    $row_rsOnline = mysql_fetch_assoc($rsOnline);
    $totalRows_rsOnline = mysql_num_rows($rsOnline);
    $colname_rsCommentby = "-1";
    if (isset($_SESSION['MM_Username'])) {
      $colname_rsCommentby = $_SESSION['MM_Username'];
    mysql_select_db($database_ezzyConn, $ezzyConn);
    $query_rsCommentby  = sprintf("SELECT user_id, username FROM users WHERE username = %s",  GetSQLValueString($colname_rsCommentby, "text"));
    $rsCommentby = mysql_query($query_rsCommentby, $ezzyConn) or die(mysql_error());
    $row_rsCommentby = mysql_fetch_assoc($rsCommentby);
    $totalRows_rsCommentby = mysql_num_rows($rsCommentby);
    ?>
    <?php include("../includes/access.php"); ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>ezzybay - easy click, ezzy shopping</title>
    <link href="../css/global.css" rel="stylesheet" type="text/css" />
    <link href="../css/navigation.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <div id="wrapper">
      <?php include("../includes/top.php"); ?>
      <div id="content">
      <div id="pageTitle">
        <h2>CMS Section:</h2>
        <p>Comment Topics Page</p>
      </div>
      <?php include("../includes/leftnav.php"); ?>
        <div id="mainContent">
          <form action="<?php echo $editFormAction; ?>" method="post" name="frmpostComment" id="frmpostComment">
            <table align="center">
            <caption>Post Comment</caption>
              <tr valign="baseline">
                <td nowrap="nowrap" align="right">Topic:</td>
                <td><select name="com_topic" class="listbox" id="com_topic">
                  <?php
    do { 
    ?>
                   <option value="<?php echo  $row_rsTopics['topic_id']?>"><?php echo  $row_rsTopics['topic']?></option>
                  <?php
    } while ($row_rsTopics = mysql_fetch_assoc($rsTopics));
      $rows = mysql_num_rows($rsTopics);
      if($rows > 0) {
          mysql_data_seek($rsTopics, 0);
          $row_rsTopics = mysql_fetch_assoc($rsTopics);
    ?>
                </select></td>
              </tr>
              <tr valign="baseline">
                <td nowrap="nowrap" align="right">Title:</td>
                <td><input name="title" type="text" class="textfield" value="" size="32" /></td>
              </tr>
              <tr valign="baseline">
                <td nowrap="nowrap" align="right" valign="top">Comment:</td>
                <td><textarea name="com_content" cols="50" rows="5" class="textarea"></textarea></td>
              </tr>
              <tr valign="baseline">
                <td nowrap="nowrap" align="right">Status:</td>
                <td><select name="online_id" class="smalllistbox">
                  <?php
    do { 
    ?>
                   <option value="<?php echo $row_rsOnline['online_id']?>"  <?php if (!(strcmp($row_rsOnline['online_id'], 2))) {echo  "SELECTED";} ?>><?php echo  $row_rsOnline['online']?></option>
                  <?php
    } while ($row_rsOnline = mysql_fetch_assoc($rsOnline));
    ?>
                </select></td>
              </tr>
              <tr> </tr>
              <tr valign="baseline">
                <td nowrap="nowrap" align="right"> </td>
                <td><input type="submit" class="button" value="Insert record" /></td>
              </tr>
            </table>
            <input name="commentby" type="hidden" id="commentby" value="<?php echo $row_rsCommentby['user_id']; ?>" />
            <input type="hidden" name="com_date" value="<?php echo date("d/m/y : H:i:s", time()) ?>" />
            <input type="hidden" name="MM_insert" value="frmpostComment" />
          </form>
        </div>
      </div>
    <?php include("../includes/footer.php"); ?>
    </div>
    </body>
    </html>
    <?php
    mysql_free_result($rsTopics);
    mysql_free_result($rsOnline);
    mysql_free_result($rsCommentby);
    ?>

    I'll keep it simple and only use the date as an example. Hopefully you get the concept from the example. Basically you create a recordset and insert the recordset value instead of the POST value into your insert query. In the example below I declared a variable for $the_date and entered the variable into the INSERT query instead of the hidden POST field.
    <?php require_once('../../Connections/ezzyConn.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;
    $the_date = date("d/m/y : H:i:s", time());
    $editFormAction = $_SERVER['PHP_SELF'];
    if (isset($_SERVER['QUERY_STRING'])) {
      $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
    if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "frmpostComment")) {
       $insertSQL = sprintf("INSERT INTO comments (com_topic, com_user, title,  com_content, com_date, online_id) VALUES (%s, %s, %s, %s, %s, %s)",
                           GetSQLValueString($_POST['com_topic'], "int"),
                           GetSQLValueString($_POST['commentby'], "int"),
                           GetSQLValueString($_POST['title'], "text"),
                           GetSQLValueString($_POST['com_content'], "text"),
                           GetSQLValueString($the_date, "text"),
                           GetSQLValueString($_POST['online_id'], "int"));
      mysql_select_db($database_ezzyConn, $ezzyConn);
      $Result1 = mysql_query($insertSQL, $ezzyConn) or die(mysql_error());
      $insertGoTo = "index.php";
      if (isset($_SERVER['QUERY_STRING'])) {
        $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
        $insertGoTo .= $_SERVER['QUERY_STRING'];
      header(sprintf("Location: %s", $insertGoTo));
    ?>

  • Checking the status of the insert query in JSP

    frendz,
    i am working with JSP .i have some content to be inserted in the database.i have used the insert query in SQL for that.i am able to check whether it has been inserted properly in the SQL but i want to check the status of the insert query with its return value(so that i can confirm it does not return a error).so please help.

    The Statement#executeUpdate() returns an int with the row count. Get hold of it.
    Also see the Statement API: http://java.sun.com/javase/6/docs/api/java/sql/Statement.html
    Apart from this, I recommend you to use PreparedStatement instead. It will not only ease setting Java objects in a query (no hassle anymore with quotes), but it will also prevent you from SQL injections.
    Prepare here: http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html
    SQL injections: http://en.wikipedia.org/wiki/SQL_injection

Maybe you are looking for