MySql select statement

Hi All,
I have java application which suppose to connect to MySql server and print the selected data.
The application has 4 combo boxes (first item is empty): Name, Customer, Supplier, Status.
User could choose any of these options. So there are huge number of select combinations.
Is it possible to create one select statement template something like this:
PreparedStatement stmt = con.prepareStatement( "SELECT * from database WHERE user_id = ?,
and customer_id = ?,
and supplier_id = ?,
and status = ? " );
if ( ! ComboBox.getSelectedItem().toString().isEmpty() )
stmt00.setString( 1, ComboBox.getSelectedItem().toString() );
else
stmt00.setString( 1, "*" );
etc…
I'm stuck at this part stmt00.setString( 1, "*" ). Is there any way to write statement SELECT * from table WHERE column = * ?
What is the proper way to write such selection ?
Thanks in advance,
Vladimir

Is there any way to write statement SELECT * from table WHERE column = * ?No, that's invalid SQL.
What is the proper way to write such selection ?If you need in one case to select a single user, but in another case to select all of them, then you need to handle two different SQL statements.
1. SELECT * from table WHERE column = value
2. SELECT * from table
This has nothing to do with Java.

Similar Messages

  • Conditional Mysql select statement

    HI Folks
    can anyone point me in the right direction with a MySQL statement.
    I will try to layout my thinking here:
    I have a form with three inputs area, name and search. I am trying to write a Mysql select statement that selects records from a single table if they match the criteria. Easy for two variables but I'm lost after that.
    1. The form includes these three inputs:
    area - drop down menu (Any as default)
    name - drop down menu (Any as default)
    search box - text area (Blank as default)
    2. The form submits to itself leaving me with these three variables
    $search=$_GET['search']
    $area=$_GET['area']
    $name=$_GET['area']
    SELECT * FROM database WHERE database.description LIKE '%$search%' AND database.area LIKE '$area' AND database.name LIKE '$name'
    3. This is where I get confused. How do I get the SQL to Select everything correctly. I have tried using PHP if/else code to fix it but I end up running around in circles with six different Select statements and haven't yet got that to work.
    So I have come to the conclusion that there must be an easier way.  I see search forms with dozens of  search criteria on websites every day an d I only have 3 - so it can't be this complicated. Right?
    I know I need to start from the beginning again but can anyone let me know how to approach it before I begin?
    Cheers
    Dave

    Typically, I would build the where clause dynamically, based upon the values in your form. If the form field contains 'Any', leave it out of the where clause. So you can test each field value and either append or not to the end of the where clause.

  • MySQL Select Statement Help Required

    I am trying to generate a report in VS 2008 (C#) using a mysql select statement but cannot get it right.
    I have groups that meet on a weekly basis on different days. I want to generate a report that shows me all the members that have not attended their group where they have missed 3 meetings in a row.
    Below is the select statement I have tried but it does not give me the results I am looking for. I have tried to look at all the meetings in a 4 week period but would prefer to look at the last 3 meetings that are recorded. Some groups might not record a meeting every week. So I want to look at the last 3 recorded meetings and count each members attendance and only report on the members with more than 3 meetings missed.
    SELECT COUNT(`groupattendance`.`Attended`) AS Attendance, `smallgroupform`.`MeetingDate`, `userinfo`.`FirstName`, `userinfo`.`Surname`, `smallgroup`.`GroupName`, `groupattendance`.`Attended`, `groupattendance`.`UserID`, `groupattendance`.`GroupID`
    FROM ((`anatomy`.`groupattendance` `groupattendance`
    INNER JOIN `anatomy`.`smallgroupform` `smallgroupform` ON `groupattendance`.`FormID` = `smallgroupform`.`FormID`)
    INNER JOIN `anatomy`.`userinfo` `userinfo` ON `groupattendance`.`UserID` = `userinfo`.`UserID`)
    INNER JOIN `anatomy`.`smallgroup` `smallgroup` ON `groupattendance`.`GroupID` = `smallgroup`.`GroupID`
    WHERE (`smallgroupform`.`MeetingDate` >= DATE_SUB(CURDATE(),INTERVAL 4 WEEK) AND `smallgroupform`.`MeetingDate` <= CURDATE()) AND `groupattendance`.`Attended` = 'False'
    GROUP BY `userinfo`.`UserID`
    HAVING Attendance >= 3
    Thanks,
    Garth.

    Hi Garth,
    Seems no one can help you directly. Try googling your SQL request. Someone may be able to help you. At this point its not really a Cr problem.
    One option is to get all the data and add filtering using the record selection formula.
    Thank you
    Don

  • Concat java variable to a MySql select statement and exeucte

    Hi,
    I am trying to append a variable to a MySql select statement.
    Overview: I need to retrieve data from a MySql database with a java variable as a reference and select the data in the database based on that variable.
    CODE THAT I CURRENTLY HAVE:
    // Declare variables
    Connection conn = null;
    Statement st = null;
    Resultset rs2 = null;
    String st2 = null;
    String keyid = null;
    // Connect to database
    try {
          Class.forName("org.gjt.mm.mysql.Driver").newInstance();
          conn = DriverManager.getConnection("jdbc:mysql://" + mysql_host + ":3306/" + mysql_database, mysql_login, mysql_password);
          st = conn.createStatement();
          // Select data in Database with hanging equal sign
          st2 = ("SELECT * FROM table WHERE keyid= ");
          // Append keyid to hanging equal sign of select statement
          rs2 = st.executeQuery(st2 + keyid);
    }This is not working when I try to display the data.

    What is not working about it? Is there an error message? Stack Trace?
    Where do you get the value of keyId from?
    I would suggest that you use a prepared statement rather than building up a sql string like this. It prevents sql injection attacks
    // Declare variables
    Connection conn = null;
    PreparedStatement stmt = null;
    Resultset rs2 = null;
    String sql= null;
    String keyid = null;
    // Connect to database
    try {
          Class.forName("org.gjt.mm.mysql.Driver").newInstance();
          conn = DriverManager.getConnection("jdbc:mysql://" + mysql_host + ":3306/" + mysql_database, mysql_login, mysql_password);
          // Select data in Database with place holder for parameter
          sql = "SELECT * FROM table WHERE keyid= ?";
           // prepare the statement
          stmt = conn.prepareStatement(sql);
          // set the value of key id to use with the query
          stmt.setString(1, keyId);
          // run the query
          rs2 = st.executeQuery();
    catch (Exception e){
      System.out.println("An error occurred " + e.getMessage());
      e.printStackTrace();
    finally{
      if (rs2 != null) try { rs2.close(); } catch(SQLException ex){}
      if (stmt != null) try { stmt.close(); } catch(SQLException ex){}
      if (conn != null) try { con.close(); } catch(SQLException ex){}
    }

  • MySql select statement in jsp page

    Ok,
    I need help with this select statement.
    <%
    // Determine what option is set to.
    if(option == null || "".equals(option) || "Verify1".equals(option)){
      if("Verify1".equals(option)){
      // Retrive query specific to submitted form.
      try {
          Class.forName("org.gjt.mm.mysql.Driver").newInstance();
          conn = DriverManager.getConnection("jdbc:mysql://" + mysql_host + ":3306/" + mysql_database, mysql_login, mysql_password);
          st = conn.createStatement();
          rs= st.executeQuery("SELECT organization FROM tblevent_approval WHERE MAX (keyid))";
          // Get query results.
          while(rs.next()){
            organization = rs.getString("organization");
      finally {
            if(rs != null){
              rs.close();
            if(st != null){
              st.close()
            if(conn != null){
              conn.close();
    %>THE ERROR I AM GETTING
    Syntax error, insert ")" to complete Expression

    This line has the closing bracket inside the closing quote for the statement...
    >       rs= st.executeQuery("SELECT organization FROM tblevent_approval WHERE MAX (keyid))";It should be:
    rs= st.executeQuery("SELECT organization FROM tblevent_approval WHERE MAX (keyid)");A simple typo ;-)
    Hope this helps...

  • Mysql select statement where = works and LIKE fails

    I am using Flash Builder 4. On the server side I use php and mysql. I created a php dataservice using FB4. My plan had been to allow users to enter a search term and query the database using a "LIKE" statement. FB4 created the php code that I simply modified changing the parameter name. The input parameter is a string.
    public function getT_caseByID($searchTerm) {
    $stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename WHERE (title = ?)");
    $this->throwExceptionOnError();
    mysqli_stmt_bind_param($stmt, 'i', $searchTerm);
    $this->throwExceptionOnError();
    mysqli_stmt_execute($stmt);
    $this->throwExceptionOnError();
    mysqli_stmt_bind_result($stmt, $row->idt_case, $row->title, $row->id_author, $row->comments);
    if(mysqli_stmt_fetch($stmt)) {
          return $row;
    } else {
          return null;
    A look at FB4 shows this code returns data.
    This code works fine but if I make the below change it fails, even when I use the wildcard %. the only change is "=" to "LIKE".
    public function getT_caseByID($searchTerm) {
    $stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename WHERE (title LIKE ?)");
    $this->throwExceptionOnError();
    mysqli_stmt_bind_param($stmt, 'i', $searchTerm);
    $this->throwExceptionOnError();
    mysqli_stmt_execute($stmt);
    $this->throwExceptionOnError();
    mysqli_stmt_bind_result($stmt, $row->idt_case, $row->title, $row->id_author, $row->comments);
    if(mysqli_stmt_fetch($stmt)) {
         return $row;
    } else {
         return null;
    A look into FB4 shows "void".
    Any help would be appreciated. I am using localhost on Apache Server on a development computer with Windows XP.

    correctio0n on the select statement
    select statement code*********
    select
        apspnr astspr aobjnr apspid
        bpsphi bposid
        caufnr cpspel
        dinact dstat
        eudate eusnam eutime "estat
       F~TXT04
        g~estat
        G~TXT04
        into corresponding fields of table itobj
        from proj as a
        inner join prps as b on apspnr = bpsphi
        inner join aufk as c on bpspnr = cpspel
        inner join jest as d on cobjnr = dobjnr
        inner join jcds as e on dobjnr = eobjnr
                             and dstat = estat
        inner join tj02t as f on estat = fistat
        inner join tj30t as g on astspr = gstsma
        for all entries in itparm
        where  apspid = itparm-pspid "or estat = itparm-psy )
        or  bposid = itparm-posid "or estat = itparm-wsy )
        or  caufnr = itparm-aufnr "or estat = itparm-nsy  )
        and ( dinact  'X' or einact  'X')
        and fspras = 'E' and gspras = 'E'.

  • [php+mysql] how to use variables in a select statement?

    Hi all,
    I'm searching for a way to use a variable in the select
    statement of mysql
    query.
    I have this variable that can contain:
    $var=field_1 field_2 field5
    or
    $var=field3 field4 field8
    so, the variable content is not always the same.
    I would like to filter a table selecting only the columns
    specified by the
    current $var content.
    Is this possible to do something like this?
    $var=field1 field5 field10
    SELECT string_to_array($var)
    FROM mytable
    ORDER BY mysortfield ASC
    Or, is there another way to select columns dynamically?
    Thanks for any suggestion.
    tony

    Hi all,
    I'm searching for a way to use a variable in the select
    statement of mysql
    query.
    I have this variable that can contain:
    $var=field_1 field_2 field5
    or
    $var=field3 field4 field8
    so, the variable content is not always the same.
    I would like to filter a table selecting only the columns
    specified by the
    current $var content.
    Is this possible to do something like this?
    $var=field1 field5 field10
    SELECT string_to_array($var)
    FROM mytable
    ORDER BY mysortfield ASC
    Or, is there another way to select columns dynamically?
    Thanks for any suggestion.
    tony

  • Using variable in select statement (php)

    I am having difficulty using a variable in a select
    statement.
    The following manual query (using a static date) works fine:
    $query_Recordset1 = "SELECT * FROM academyClasses WHERE
    classDate > '2006-06-01' ";
    However, If I use the following:
    $dateVar = date('Y-m-d');
    mysql_select_db($database_mw, $mw);
    $query_Recordset1 = "SELECT * FROM academyClasses WHERE
    classDate > $dateVar ";
    ALL records are returned, which means the $dateVar variable
    is not being recognized. I have compared the $dateVar values
    <?php echo $datetime; ?> against the actual value of my date
    field <?php echo $row_Recordset1['classDate']; ?> in my
    results table and it seems that the values are indeed accurate in
    terms of a date 2006-06-04 for example.
    My date field "classDate" is of a "date" type within the
    mysql database. I'm using Dreamweaver MX 2004 with Mac OSX 10.3.9.
    I'm sure this is just a syntax problem, at least I hope it
    is.
    Any help is greatly appreciated.

    On Wed, 7 Jun 2006 04:49:57 +0000 (UTC), "mgwaters"
    <[email protected]> wrote:
    >Thanks Gary. That did seem to get the select statement
    working, but I had to
    >enter a manual date as before $dateVar = '2006-06-01'; on
    the previous line of
    >code to actually get it to filter my records. So... it
    looks like my setting of
    >the date variable:
    > $dateVar = date('Y-m-d');
    > does not seem to be recognized within the SELECT
    statement.
    Try this:
    $query_Recordset1 = "SELECT * FROM academyClasses WHERE
    classDate>'$dateVar'";
    print $query_Recordset1;
    See what is in the SQL statement.
    Gary

  • Oracle database link to MySQL select only one row

    Hello,
    I have created a connection from the Oracle batabase 11.2 to a MySQL database via database link. The following statement shows, that 35 rows are in the mySQL table:
    SQL>  select count(*) from "main_pages"@MOREWEB;
      COUNT(*)
            35
    But a normal select statement only return 1 row.
    SQL> select "subject" from "main_pages"@MOREWEB;
    subject
    Übersicht: Referenzen
    I am using the mysql-connector-odbc-3.51.30-winx64 driver. A newer version cann't be installed because on Windows Server 2008 R2 I get an error with an missing dll-file. The DataDirect-ODBC-driver is not possible, because we like to use the free MySQL-database an DataDirect only support the enterprise edition.
    I also have tried to limit the HS_OPEN_CURSORS or dont limit the HS_FDS_FETCH_ROWS, but there is no difference in the result. I always get only one row.
    HS Init.ora
    # This is a sample agent init file that contains the HS parameters that are
    # needed for the Database Gateway for ODBC
    # HS init parameters
    HS_FDS_CONNECT_INFO = moreweb
    HS_FDS_TRACE_LEVEL = ON
    HS_FDS_FETCH_ROWS=1
    # Environment variables required for the non-Oracle system
    #set <envvar>=<value>
    HS tracefile
    Oracle Corporation --- MITTWOCH   NOV 05 2014 13:56:22.066
    Heterogeneous Agent Release
    11.2.0.1.0
    Oracle Corporation --- MITTWOCH   NOV 05 2014 13:56:22.066
        Version 11.2.0.1.0
    HOSGIP for "HS_FDS_TRACE_LEVEL" returned "ON"
    HOSGIP for "HS_OPEN_CURSORS" returned "50"
    HOSGIP for "HS_FDS_FETCH_ROWS" returned "1"
    HOSGIP for "HS_LONG_PIECE_TRANSFER_SIZE" returned "65536"
    HOSGIP for "HS_NLS_NUMERIC_CHARACTER" returned ".,"
    HOSGIP for "HS_KEEP_REMOTE_COLUMN_SIZE" returned "OFF"
    HOSGIP for "HS_FDS_DELAYED_OPEN" returned "TRUE"
    HOSGIP for "HS_FDS_WORKAROUNDS" returned "0"
    HOSGIP for "HS_FDS_MBCS_TO_GRAPHIC" returned "FALSE"
    HOSGIP for "HS_FDS_GRAPHIC_TO_MBCS" returned "FALSE"
    HOSGIP for "HS_FDS_RECOVERY_ACCOUNT" returned "RECOVER"
    HOSGIP for "HS_FDS_TRANSACTION_LOG" returned "HS_TRANSACTION_LOG"
    HOSGIP for "HS_FDS_TIMESTAMP_MAPPING" returned "DATE"
    HOSGIP for "HS_FDS_DATE_MAPPING" returned "DATE"
    HOSGIP for "HS_FDS_CHARACTER_SEMANTICS" returned "FALSE"
    HOSGIP for "HS_FDS_MAP_NCHAR" returned "TRUE"
    HOSGIP for "HS_FDS_RESULTSET_SUPPORT" returned "FALSE"
    HOSGIP for "HS_FDS_RSET_RETURN_ROWCOUNT" returned "FALSE"
    HOSGIP for "HS_FDS_PROC_IS_FUNC" returned "FALSE"
    HOSGIP for "HS_FDS_REPORT_REAL_AS_DOUBLE" returned "FALSE"
    using mpgw as default value for "HS_FDS_DEFAULT_OWNER"
    HOSGIP for "HS_SQL_HANDLE_STMT_REUSE" returned "FALSE"
    SQL text from hgopars, id=1, len=36 ...
         00: 53454C45 43542043 4F554E54 282A2920  [SELECT COUNT(*) ]
         10: 46524F4D 20606D61 696E5F70 61676573  [FROM `main_pages]
         20: 60204131                             [` A1]
    Deferred open until first fetch.
    Performing delayed open.
    SQL text from hgopars, id=1, len=40 ...
         00: 53454C45 43542041 312E6073 75626A65  [SELECT A1.`subje]
         10: 63746020 46524F4D 20606D61 696E5F70  [ct` FROM `main_p]
         20: 61676573 60204131                    [ages` A1]
    Deferred open until first fetch.
    Performing delayed open.
    Please can help me someone.
    Thanks.
    Bianca

    mxallen wrote:
    Bianca,
    If you log directly into MySQL and issue the same query (select "subject" from "main_pages";) what data is returned?
    I looks to me that you count is the number of rows in the entire table "main_pages"
    while you select is for the data in the "subject" column only.
    This seems to indicate that you have just one row in that subject column.
    Regards,
    Matt
    WHAATT?
    What do you mean by "just one row in that subject column"?
    That makes no sense at all.  A row is a row.  A column is a part of a row.  All rows have all columns, though not all columns of all rows will necessarily have an assigned value.  Lacking a WHERE clause to filter rows, any SELECT should return all rows.

  • Toplink Essentials creates not usable select statement

    My problem is the following:
    I have the following NamedQuery statement in an JPA Entity Class:
    @NamedQuery(name = "Leasingteilvertrag.findSearch",
    query = "select distinct o " +
    " from Leasingteilvertrag o " +
    " left outer join o.sachbearbeiterList s " +
    " where (:wtvStatusBearb1 is null or :wtvStatusBearb2 = -1 or o.wtvStatusBearb =
    :wtvStatusBearb3)" +
    " and (:wtvStatusVerwert1 is null or :wtvStatusVerwert2 = -1 or o.wtvStatusVerwert = :wtvStatusVerwert3)" +
    " and (:wtvAdressNr1 is null or :wtvAdressNr2 = -1 or o.wtvAdressNr =
    :wtvAdressNr3)" +
    " and (:wtvEingangsdatum1 is null or o.wtvEingangsdatum >= :wtvEingangsdatum2)" +
    " and (:wtvEingangsdatumBis1 is null or o.wtvEingangsdatum <= :wtvEingangsdatumBis2)"
    +
    " and (:wtvLlvNr1 is null or o.wtvLlvNr = :wtvLlvNr2)" +
    " and (:wtvFirma1 is null or o.wtvFirma = :wtvFirma2)" +
    " and (:wsbId1 is null or :wsbId2 = -1 or s.wsbSbId = :wsbId3)")
    Oracle Toplink translates this (according to to opmn log of the Application Server)
    to:
    SELECT DISTINCT t0.WTV_ID, t0.WTV_SL_PLUS_KNZ, t0.WTV_ABGESCHLOSSENDATUM, t0.WTV_SL_TECHNIK_DATE, t0.WTV_ADRESS_POOL, t0.WTV_SL_TECHNIK_KNZ,
    t0.WTV_AKTENZEICHEN_RA, t0.WTV_SONDERAFA_OBJEKTE_AKTUELL,
    t0.WTV_ANZAHLRUECKSTAENDIGERRATEN, t0.WTV_SONDERAFA_OBJEKTE_GEBUCHT,
    t0.WTV_BANKAUSKUNFT_KNZ, t0.WTV_STATUS_BEARB, t0.WTV_EINGANGSDATUM,
    t0.WTV_STATUS_BEARB_DATUM, t0.WTV_EINSCHAETZUNG_BONI, t0.WTV_STATUS_VERWERT,
    t0.WTV_EWB_DATUM_ERFASSUNG, t0.WTV_STATUS_VERWERT_DATUM, t0.WTV_EWB_GEBUCHT,
    t0.WTV_STATUS_FREIGABE, t0.WTV_EWB_SB_ERFASSUNG, t0.WTV_STATUS_FREIGABE_DATUM,
    t0.WTV_FIRMA, t0.WTV_VERBLEIB_AKTE, t0.WTV_WAEHRUNG_AUSFALL,
    t0.WTV_KUENDIGUNGSFORDERUNG, t0.WTV_WAEHRUNG_EWB, t0.WTV_LLV_NR,
    t0.WTV_WAEHRUNG_RUECKST_ANR, t0.WTV_LTV_NR, t0.WTV_WAEHRUNG_SONDERAFA_OBJEKTE,
    t0.WTV_PROZESSKOSTEN_RISIKO, t0.WTV_WAE_EINSCHAETZUNG_BONI,
    t0.WTV_RUECKST_ANRECHNUNG_GEBUCHT, t0.WTV_WAE_KUENDIGUNGSFORDERUNG,
    t0.WTV_SL_KASKO_DATE, t0.WTV_WIEDERGESUNDUNGSDATUM, t0.WTV_SL_PLUS_DATE,
    t0.WTV_ABGESCHLOSSEN_KNZ, t0.WTV_AKTENZEICHEN_FAV, t0.WTV_TEILRISIKO_KNZ,
    t0.WTV_AUSFALL, t0.WTV_BETRUG_KNZ, t0.WTV_EINGANGSDATUM_ALT,
    t0.WTV_CHANGE_USER, t0.WTV_EWB_DATUM_FREIGABE, t0.WTV_CHANGE_DATE,
    t0.WTV_EWB_SB_FREIGABE, t0.WTV_FREIGABE_KOMMENTAR, t0.WTV_KUENDIGUNGSDATUM,
    t0.WTV_ADRESS_NR, t0.WTV_ALTFALL_KNZ, t0.WTV_OPERATIONELLES_RISIKO,
    t0.WTV_BEMERKUNG, t0.WTV_SACHSTAND, t0.WTV_EWB_AKTUELL,
    t0.WTV_LLV_NR_UMFINANZIERUNG, t0.WTV_EWB_KORREKTUR, t0.WTV_SL_KASKO_KNZ,
    t0.WTV_FIRMA_UMFINANZIERUNG, t0.WTV_RUECKST_ANRECHNUNG_AKTUELL,
    t0.WTV_KUENDIGUNGSFORDERUNG_ALT, t0.WTV_LEASINGVERTRAG_ID,
    t0.WTV_RUECKST_ANRECHNUNG_BUC_ID, t0.WTV_EWB_BUC_ID,
    t0.WTV_SONDERAFA_OBJEKTE_BUC_ID FROM VWDB_LEASINGTEILVERTRAG t0,
    VWDB_LEASINGTEILVERTRAG t2, VWDB_SACHBEARBEITER t1 WHERE (((((((((((? IS NULL)
    OR (? = (? - ?))) OR (t0.WTV_STATUS_BEARB = ?)) AND (((? IS NULL) OR (? = (? -
    ?))) OR (t0.WTV_STATUS_VERWERT = ?))) AND (((? IS NULL) OR (? = (? - ?))) OR
    (t0.WTV_ADRESS_NR = ?))) AND ((? IS NULL) OR (t0.WTV_EINGANGSDATUM > ?))) AND
    ((? IS NULL) OR (t0.WTV_EINGANGSDATUM < ?))) AND ((? IS NULL) OR (t0.WTV_LLV_NR
    = ?))) AND ((? IS NULL) OR (t0.WTV_FIRMA = ?))) AND (((? IS NULL) OR (? = (? -
    ?))) OR (t1.WSB_SB_ID = ?))) AND (t1.WSB_LTV_ID (+) = t0.WTV_ID))
    The Problem is the "VWDB_LEASINGTEILVERTRAG t2" entry in the FROM clause of the generated select statement. This causes the select to generate the cartesian product.
    Has anyone had such a problem before? How can this be solved?

    Hello,
    I have exactly the same problem (with a simpler query though). I'm running my webapp on a GlassFish V2 (build b09d-fcs), Toplink Essentials JPA impl. and a MySQL 6.0.4 database server.
    I'm trying to run the following JPQL query: select f from Foo f where (1=1) and f.title = :title
    After having set persistence log levels to FINE, the following SQL is displayed:
    select t0.XXX, t0.YYY from Foo t0, Foo t1 where ((?=?) and (t0.title= ?))
    bind => [1, 1, Bar]
    (1 = 1) is used because of dynamic query generation (application code)
    The problem is that the additional from clause is generating a cartesian product on my Foo table, which causes many duplicated results to be returned.
    I have simplified the select part of the query but the actual query is of the same kind: no join, only 1 entity, no inheritance, a single N:1 lazy-initialized entity (*Foo-1FooParent). The only "exotic" facet of my Foo mapping is the use of an @Enumerated column.
    Is it the expected behavior?
    -Titix

  • Problems with PreparedStatement and MySQL selecting bytes

    Hi,
    i have a problem trying to select information when the "select" has a byte restrict.
    The table in database is:
    CREATE TABLE `positions` (
    `PKID` int(10) unsigned NOT NULL auto_increment,
    `POSCODE` varbinary(30) NOT NULL,
    `ISWTURN` binary(1) NOT NULL,
    `QTT_GAMES` int(10) unsigned NOT NULL default '1',
    PRIMARY KEY (`PKID`),
    UNIQUE KEY `UNIQ_POS` (`POSCODE`,`ISWTURN`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    And the test code to get the qtt_games is :
    conn = DriverManager.getConnection (url,user,pwd);
    byte bcode[] = poscode.getByteArrayCode();
    // bcode is inserted ok in another preparedstatement...
    String query = "SELECT qtt_games FROM positions "+
         "WHERE poscode=? and iswturn=?";
    PreparedStatement pstmt = conn.prepareStatement(query);
    pstmt.setBytes (1,bcode);
    pstmt.setByte (2,poscode.getIsWhiteTurn()); //it returns a byte
    ResultSet rs = pstmt.executeQuery (query);
    When pstmt.executeQuery is reached, it's thrown the exception:
    com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: 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 '=? and iswturn=?' at line 1
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1665)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3170)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3099)
    at com.mysql.jdbc.Statement.execute(Statement.java:695)
    at app.server.bbdd.MYSQLBDManager.getGamesBasicInfo(MYSQLBDManager.java:942)
    at app.server.bbdd.MYSQLBDManager.main(MYSQLBDManager.java:1068)
    Can anybody tell me what's wrong?? I think the query is ok, but don't know what's happening with this...
    Lots of thanks.

    Don't cross-post, it's considered rude:
    http://forum.java.sun.com/thread.jspa?threadID=5122604&messageID=9430056#9430056
    http://forum.java.sun.com/thread.jspa?threadID=5122603&messageID=9430050#9430050
    One to a customer, please.
    %

  • Create an Encapsulation of Select * Statements?

    I'm looking to encapsulate a mysql db call that returns a large result set due to Select *. I prefer to return the results and let the calling routine parse (or display) the data. Unfortunately most of the methods I've tried -- multidimensional arrays, objects, returning the result set itself -- I have either run in to issues or the solution was less than ideal. I've posted some code below.
    If anyone could suggest an excellent method for handling this issue it would be appreciated. Sample code would be even better!
    Thanks in advance.
    try{
    Statement st = con.createStatement();
    /* ResultSet res = st.executeQuery("SELECT * FROM MyTable"); */
    ResultSet rs = st.executeQuery(SQLQuery);
    ResultSetMetaData rsmd = rs.getMetaData();
    int numberOfColumns = rsmd.getColumnCount() + 1;
    RowSetDynaClass rsdc = new RowSetDynaClass(rs);
    List rowset = rsdc.getRows();
    int rowcount = rowset.size() + 1;
    Object[][] arr = new Object[rowcount][numberOfColumns];
    for (int i = 1; i < rowcount; i++) {
    /* read row */
    rs.absolute(i);
    for (int j = 1; j < numberOfColumns; j++){
    /* select column from row */
    arr[i][j] = rs.getString(j);
    /* System.out.println("Value arr: " + arr[i][j]); */
    con.close();
    return arr;

    As promised in an earlier in the thread, here is my working code. It'll dynamically create an array, fill it with data and pass it back to the calling routine. Good for any select statement but I would refrain from ones that select too much data.... It's good for my project but may not be great for yours..... Enjoy....
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.List;
    import org.apache.commons.beanutils.RowSetDynaClass;
    /* need to put a class here!!! */
    public static void main(String[] args) throws SQLException {
              String SQLquery = "SELECT * FROM MyTable;";
              Object[][] rs = DBConnect.connectSELECT(SQLquery);
              int rows = rs.length;
              int cols=0;
              boolean flag = true;
              /* here we get column dimensions of array */
              while (flag) {
                   try {
                   System.out.println("Value arr: " + rs[1][cols++]);
                   } catch (IndexOutOfBoundsException kenb){
                        flag = false;
              /* here we print out table for old times sake */
              for (int i = 1; i < rows; i++) {
                        for (int j = 1; j < cols -1; j++){
                             System.out.println("Value rs: " + rs[i][j]);
    public static Object[][] connectSELECT(String SQLQuery){
              System.out.println(SQLQuery);
                Connection con = null;
                String url = "jdbc:mysql://localhost:3306/";
                String db = "MyDB";
                String driver = "com.mysql.jdbc.Driver";
                String user = "UserID";
                String pass = "UserPWD";
                try{
                          Class.forName(driver).newInstance();
                          con = DriverManager.getConnection(url+db, user, pass);
                               try{
                                    Statement st = con.createStatement();
                                    ResultSet rs = st.executeQuery(SQLQuery);
                                    ResultSetMetaData rsmd = rs.getMetaData();
                                    int numberOfColumns = rsmd.getColumnCount() + 1;
                                    RowSetDynaClass rsdc = new RowSetDynaClass(rs);
                                    List rowset = rsdc.getRows();
                                    int rowcount = rowset.size() +1;
                                  System.out.println("Rows =" + rowcount + " - Cols =" + numberOfColumns);
                                    Object[][] arr = new Object[rowcount][numberOfColumns];
                                    for (int i = 1; i < rowcount; i++) {
                                         /* read row */
                                         rs.absolute(i);
                                         for (int j = 1; j < numberOfColumns; j++){
                                                   /* select column from row */
                                              arr[i][j] = rs.getString(j);
                                              System.out.println("Value arr: " + arr[i][j] + " - i="+i + " j="+j);
                                    con.close();
                                    return arr;
                               catch (SQLException s){
                                    System.out.println("SQL code does not execute: " + s);
                                    /* on error return null */
                catch (Exception e){
                     e.printStackTrace();
              return null;
         }

  • Help with a simple select statement

    $x = oci_parse($c, "select quantity from balance where item_num=101");
    oci_execute($x);
    echo "the quant is: ".$x;
    I try to run this select statement without success
    then I tried...
    $x = oci_parse($c, "select quantity from balance where item_num=101");
    $y= oci_execute($x);
    echo "the quant is: ".$y;
    and it didn't work either...
    What should I change?
    thanks!

    The Oracle library operates a bit differently from some other PHP libraries, notably MySQL/MySQLi. With Oracle (OCI8), you have to execute the statement, and then afterward use an oci_fetch...() function to pull things from your $statement variable. Here's a small example that hopefully will illustrate the basic usage:
    <?php
         $conn = oci_connect('hr','hr','xe');
         if(!$conn) {
              echo 'Could not connect!';
              exit;
         $sql = 'select * from jobs';
         $stmt = oci_parse($conn, $sql);
         if(!$stmt) {
              echo 'Could not parse query.';
              exit;
         $result = oci_execute($stmt, OCI_DEFAULT);
         if(!$result) {
              echo 'Could not execute query.';
              exit;
         echo "Query ran successfully.\n";
         // Fetch rows as associative arrays, so
         // we can ask for values by column name.
         // Other options include oci_fetch_row(),
         // oci_fetch_array(), and oci_fetch_object().
         // Note that oci_fetch_assoc() will create
         // an associative array using upper-case
         // column names for the keys.
         while(($row = oci_fetch_assoc($stmt)) != null)
              echo $row['JOB_ID'] . ': ' . $row['JOB_TITLE'] . "\n";
         echo "All data returned.\n";
         oci_close($conn);
    ?>When I run this, I get the following:
    C:\workspace\php>php select.php
    Query ran successfully.
    AD_PRES: President
    AD_VP: Administration Vice President
    AD_ASST: Administration Assistant
    FI_MGR: Finance Manager
    FI_ACCOUNT: Accountant
    AC_MGR: Accounting Manager
    AC_ACCOUNT: Public Accountant
    SA_MAN: Sales Manager
    SA_REP: Sales Representative
    PU_MAN: Purchasing Manager
    PU_CLERK: Purchasing Clerk
    ST_MAN: Stock Manager
    ST_CLERK: Stock Clerk
    SH_CLERK: Shipping Clerk
    IT_PROG: Programmer
    MK_MAN: Marketing Manager
    MK_REP: Marketing Representative
    HR_REP: Human Resources Representative
    PR_REP: Public Relations Representative
    All data returned.
    C:\workspace\php>For more information, take a look at the OCI8 library documentation in the PHP manual online:
    OCI8
    http://us.php.net/manual/en/book.oci8.php
    Some other examples
    http://us.php.net/manual/en/oci8.examples.php
    Kind regards,
    Christopher L. Simons

  • If statement in select statement alias

    I have the following select statement. It has the alias Survivors, Deaths and "All Cases". Is it posible to use :P_LANGUAGE variable to say that -- IF :P_LANGUAGE = FRENCH THEN alias are Survivants for survivors, Décès for Deaths, Tous_les_cas for All Cases. Please advise
    SELECT ALL T_NTR_MULTIBAR.CAT, T_NTR_MULTIBAR.NUM_CASES_LEFTBAR AS Survivors,
    T_NTR_MULTIBAR.NUM_CASES_MIDDLEBAR AS Deaths, T_NTR_MULTIBAR.NUM_CASES_RIGHTBAR AS "All Cases"
    FROM T_NTR_MULTIBAR
    WHERE INSTANCE_NUM = :P_INSTANCENUM
    order by ORDERS

    You may not be able to add this condition inside the SQL Statement. But you can add this condition outside the statement, if you're using PL/SQL...
    IF :p_language = french THEN
    SELECT ALL t_ntr_multibar.cat,
      t_ntr_multibar.num_cases_leftbar AS survivors,
      t_ntr_multibar.num_cases_middlebar AS deaths,
      t_ntr_multibar.num_cases_rightbar AS "All Cases"
    ELSE
    END IF;

  • How to get all values from an interval using select statement

    Hi,
    Is it possible to write a select statement that returns all values from an interval? Interval boundaries are variable.
    something like this:
    select (for x in 1,1024 loop x end loop) from dual
    (this, of course, doesn't work)
    The result in this example should be 1024 rows of numbers from 1 to 1024. These numbers are parameters, so it is not possible to create a table with predefined values.
    Thanks in advance for your help,
    Mia.

    For your simple case, with a lower boundary of 1, you can use:
    SELECT rownum
    FROM all_objects
    WHERE rownum <= 1024For a set of number between say 50 - 100, you can use something like:
    SELECT rownum + (50 - 1)
    FROM all_objects
    WHERE rownum <= (100 - 50 + 1)Note, that all_objects was used only because it generally has a lot of rows. Any table with at least the number of rows in your range will work.
    TTFN
    John

Maybe you are looking for

  • Failed to install enterprise manager under linux

    When I installed Oracle 10g(10.2.0.1) under linux, I got an error when running /ora01/db/oracle/product/10.2.0.1/bin/emca within oracle universal installer. The emConfig.log file shows such error: oracle.sysman.emcp.exception.EMConfigException: Inval

  • Errors for foreign payments in the APP run

    HI all we have created new house bank for foreign payments for foreign vendors. The bank has been created for domestic payments and for foreign payment for the company code. The  domestic payment works fine and the international does not work. It can

  • Viewing videos on TV

    Hi...Thanks in advance for any help you may have. Is it possible to view the videos that I download on a TV via a Playstation 2 game console? I plan to burn them to a disc.

  • How to disable the print icon on check status screen of shopping cart inSRM

    Hi Experts, I have a requirment in which I need to disable print Icon on the status screen of the shopping cart. Can anybody please let me know how to achive this requirement. Thanks, Arun K Singarapu

  • Related to call

    When ever I have reset networking setting,some times I am unable call  to anybody it showing call failed