How to check the value from user input in database or not?

Hello;
I want to check the value of user input from JtextFiled in my database or not.
If it is in database, then i will pop up a window to tell us, otherwise, it will tell us it is not in database.
My problem is my code do not work properly, sometimes, it tell me correct information, sometime it tell wrong information.
Could anyone help,please.Thanks
The following code is for check whether the value in database or not, and pop up a window to tell us.
while( rs.next()) {
                System.out.println("i am testing");
                bInt=new Integer(rs.getInt("id"));
                if(aInt.equals(bInt)){ // If i find the value in data base, set flag to 1.
              flag=1;  //I set a flag to check whether the id in database or not
                    break;
         System.out.println("falg" + flag);
            if(flag==1){ //?????????????????????
          String remove1 = "DELETE FROM Rental WHERE CustomerID=" + a;
          String remove2 = "DELETE FROM Revenus WHERE CustomerID=" +a;
          String remove3 = "DELETE FROM Customer WHERE id=" +a;
          s.executeUpdate(remove1);
          s.executeUpdate(remove2);
          s.executeUpdate(remove3);
                JOptionPane.showMessageDialog(null,"you have success delete the value");
          s.close();
         else//???????????????????????????????
              JOptionPane.showMessageDialog(null,"I could not found the value"); -------------------------------------------------------------------
My whole program
import java.sql.*;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class DeleteC extends JFrame
    public static int index=0;   
    public static ResultSet rs;
    public static Statement s;
    public static Connection c;
    public static  Object cols[][];
    private static JTable table;
    private static JScrollPane scroller;
    private static int flag=0;
    public DeleteC()
        //information of our connection
        //the url of the database: protocol:subprotocol:subname:computer_name:port:database_name
        String strUrl      = "jdbc:oracle:thin:@augur.scms.waikato.ac.nz:1521:teaching";
        //user name and password
        String strUser      = "xbl1";
        String strPass      = "19681978";
        //try to load the driver
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        catch (ClassNotFoundException e) {
            System.out.println( "Cannot load the Oracle driver. Include it in your classpath.");
            System.exit( -1);
        //a null reference to a Connection object
        c = null;
        try {
            //open a connection to the database
            c = DriverManager.getConnection( strUrl, strUser, strPass);
        catch (SQLException e) {
            System.out.println("Cannot connect to the database. Here is the error:");
            e.printStackTrace();
            System.exit( -1);
       //create a statement object to execute sql statements
    public void getData(String a){
        try {
         //create a statement object to execute sql statements
         s = c.createStatement();
            int index=0;
            Integer aInt= Integer.valueOf(a);
            Integer bInt;
              //our example query
            String strQuery = "select id from customer";
            //execute the query
            ResultSet rs = s.executeQuery( strQuery);
            //while there are rows in the result set
            while( rs.next()) {
                System.out.println("i am testing");
                bInt=new Integer(rs.getInt("id"));
                if(aInt.equals(bInt)){
              //JOptionPane.showMessageDialog(null,"I found the value"); 
              flag=1;
                    break;
         System.out.println("falg" + flag);
            if(flag==1){
          String remove1 = "DELETE FROM Rental WHERE CustomerID=" + a;
          String remove2 = "DELETE FROM Revenus WHERE CustomerID=" +a;
          String remove3 = "DELETE FROM Customer WHERE id=" +a;
          s.executeUpdate(remove1);
          s.executeUpdate(remove2);
          s.executeUpdate(remove3);
                JOptionPane.showMessageDialog(null,"you have success delete the value");
          s.close();
         else
              JOptionPane.showMessageDialog(null,"I could not found the value");
        catch (SQLException e) {
             JOptionPane.showMessageDialog(null,"You may enter wrong id");
My main program for user input from JTextField.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JOptionPane;
import java.util.*;
public class EnterID extends JFrame{
    public JTextField tF1;
    public EnterID enID;
    public String tF1Value;
    private JLabel label1, label2, label3;
    private static JButton button;
    private static ButtonHandler handler;
    private static String aString;
    private static Integer aInteger;
    private static Integer checkV=0;
    public static void main(String args[]){
       EnterID eId= new EnterID();
   public EnterID(){
      handler=new ButtonHandler();
      Container c= getContentPane();
      c.setLayout(new GridLayout(3,1));
      button= new JButton("ok");
      button.addActionListener(handler);
      label1 = new JLabel(" CustomerID, Please");
      label2 = new JLabel("Label2");
      label3 = new JLabel();
      label3.setLayout(new GridLayout(1,1));
      label3.add(button);
      label2.setLayout(new GridLayout(1,1));
      aString = "Enter Id Here";
      tF1 = new JTextField(aString);
      label2.add(tF1);
      c.add(label1);
      c.add(label2);         
      c.add(label3);            
      setSize(150,100);
      setVisible(true);     
   private class ButtonHandler implements ActionListener{
     public void actionPerformed(ActionEvent event){
         tF1Value=tF1.getText();
        //   CheckData cData = new CheckData();
         //  aInteger = Integer.valueOf(tF1Value);      
         if(tF1Value.equals(aString)){
          JOptionPane.showMessageDialog(null,"You didn't type value into box");
          setVisible(false); 
        else {
            DeleteC dC= new DeleteC();
            dC.getData(tF1Value);
            setVisible(false); 
}

You may have working code now, but the code you posted is horrible and I'm going to tell you a much much much better approach for the JDBC part. (You should probably isolate your database code from your user interface code as well, but I'm skipping over that structural problem...)
Do this instead:
    public void getData(String a){
        PreparedStatement p;
        String strQuery = "select count(*) the_count from customer where id = ?";
        try {   
         //create a prepared statement object to execute sql statements, it's better, faster, safer
         p = c.prepareStatement(strQuery);
            // bind the parameter value to the "?"
            p.setInt(1, Integer.parseInt(a) );
            //execute the query
            ResultSet rs = p.executeQuery( );
            // if the query doesn't throw an exception, it will have exactly one row
            rs.next();
            System.out.println("i am testing");
            if (rs.getInt("the_count") > 0 ) {
            // it's there, do what you need to...
         else
              JOptionPane.showMessageDialog(null,"I could not find the value");
        catch (SQLException e) {
             // JOptionPane.showMessageDialog(null,"You may enter wrong id");
             // if you get an exception, something is really wrong, and it's NOT user error
        // always, always, ALWAYS close JDBC resources in a finally block
        finally
            p.close();
    }First, this is simpler and easier to read.
Second, this retrieves just the needed information, whether or not the id is in the database. Your way will get much much slower as more data goes into the database. My way, if there is an index on the id column, more data doesn;t slow it down very much.
I've also left some important points in comments.
No guarantees that there isn't a dumb typo in there; I didn't actually compile it, much less test it. It's at least close though...

Similar Messages

  • How to change the value from one input control to another input control?

    Hi Experts,
    I want to change the value from  one input control to another input control. For Example if i change month in first tab. it should reflect in second tab also. How should we acheive through input control or some other option.
    Here I attached screen shot.Please help me for this

    Hi,
    It is not possible to have Input controll in all tabs that will be set from another .
    But There is one workaround .
    Follow the link below .
    http://davidlai101.com/blog/2013/08/13/web-intelligence-input-control-that-affects-all-tabs/

  • How to calculate the total from users input in switch?

    I dont know how to hold the input from user. But here is part of my coding :
    System.out.println ("Type 1 for buying Ruler"+
    "\nType 2 for buying Pencil");
    stationaries = console.nextInt();
    switch (stationaries)
    case 1 : System.out.println("Ruler per unit : MYR1");
    System.out.println("How much does you want? : ")
    wantRuler = console.nextInt();
    sum = wantRuler * 1;
    break;
    case 2 : System.out.println("Pencil per unit : MYR2");
    System.out.println("How much does you want? : ")
    wantPencil = console.nextInt();
    sum = wantPencil * 2;
    break;
    How can I calculate the total for both of the stationaries if user wants 5 for ruler and 6 for pencil?

    Note: This thread was originally posted in the [Java Programming|http://forums.sun.com/forum.jspa?forumID=31] forum, but moved to this forum for closer topic alignment.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.

  • Read the value of user input variable during calculation of virtual char

    Hello
    Virtual characteristics is populated in custom BAPI based on values specified by user in the variable screen.
    How to read the value of user input variable outside the user exit for custom variables?
    The one way is to create faked user exit variable, read the value of user input variable in corresponding FM and insert it into table. Then value of this variable will be derived from the table.  
    Thanks

    no answer

  • How to get the values from popup window to mainwindow

    HI all,
       I want to get the details from popup window.
          i have three input fields and one search button in my main window. when i click search button it should display popup window.whenever i click on selected row of the popup window table ,values should be visible in my main window input fields.(normal tables)
       now i am able to display popup window with values.How to get the values from popup window now.
       I can anybody explain me clearly.
    Thanks&Regards
    kranthi

    Hi Kranthi,
    Every webdynpro component has a global controller called the component controller which is visible to all other controllers within the component.So whenever you want to share some data in between 2 different views you can just make it a point to use the component controller's context for the same. For your requirement (within your popups view context) you will have have to copy the component controllers context to your view. You then will have to (programmatically) fill this context with your desired data in this popup view. You can then be able to read this context from whichever view you want. I hope that this would have made it clear for you. Am also giving you an [example|http://****************/Tutorials/WebDynproABAP/Modalbox/page1.htm] which you can go through which would give you a perfect understanding of all this. In this example the user has an input field in the main view. The user enters a customer number & presses on a pushbutton. The corresponding sales orders are then displayed in a popup window for the user. The user can then select any sales order & press on a button in the popup. These values would then get copied to the table in the main view.
    Regards,
    Uday

  • How to get the value from textInput Component to perform calculation?

    I need some help here...I'm trying to get the value of user input from the TextInput Component which is the age, height and weight to calculate the bmr and display the result in member("result").text.
    How am i suppose to let the integer pass through in order for me to perform calculation? Would appreciate if anyone can help me out with this, thanks!
    Below are the formula :
    The Harris Benedict equation estimates BMR:
    For women: (9.56 x w) + (1.85 x h) – (4.68 x a) + 655
    For men: (13.75 x w) + (5 x h) – (6.76 x a) + 66

    Assumed that this section is only for male ...it still show error saying script error : String expected for
    on mouseDown
       member("result").text = (13.75 * value(member("weightText").text)) + (5 * value(member("heightText").text)) - (6.76 * value(member("ageText").text)) + 66
    end
    Do i have to add in "put sprite(x).text -- where x is the number of the sprite that is the text input." ?

  • How to get the value from a JavaScript and send the same to Java file?

    Hi.
    How to get the value from a JavaScript (this JS is called when an action invoked) and send the value from the JS to a Java file?
    Thanks and regards,
    Leslie V

    Yes, I am trying with web application.
    In the below code, a variable 'message' carries the needed info. I would like to send this 'message' variable with the 'request'.
    How to send this 'message' with and to the 'request'?
    Thanks for the help :-)
    The actual JS code is:
    function productdeselection()
    var i=0;
    var j=0;
    var deselectedproduct = new Array(5);
    var message = "Are you sure to delete Product ";
    mvi=document.forms[0].MVI;
    mei=document.forms[0].MEI;
    lpi=document.forms[0].LPI;
    if(null != mvi)
    ++i;
    if(null != mei )
    ++i;
    if(null != lpi)
    ++i;
    if(null != mvi && mvi.checked)
    deselectedproduct[++j]="MVI?";
    if(null != mei && mei.checked)
    deselectedproduct[++j]="GAP?";
    if(null != lpi && lpi.checked)
    deselectedproduct[++j]="LPI?";
    if( 0!=j)
    if(i!=j)
    for (x=0; x<deselectedproduct.length; x++)
    if(null != deselectedproduct[x])
    message =message+ "-" +deselectedproduct[x];
    alert(message);
    else
    //alert(" You cannot remove all products!");
    return false;
    return true;
    }

  • How to get the value from databank

    Hi,
    How to get the value from databank? and how to set the same value to visual script object?
    thanks,
    ra

    Hi,
    You can use GetDatabankValue(HeaderName, Value) to get the value from databank and SetDataBankValue(HeaderName, Value) to set the value to databank.
    You can refer to the API Reference to see list of associated functions and techniques we can use with related to Data Bank.
    This is the for OFT but if you are using Open Script then you have direct access for getting the databank value but when it comes to setting a value you have to use File operation and write you own methods to do the set operation.
    Thanks
    Edited by: Openscript User 100 on Nov 13, 2009 7:01 AM

  • How to retrieve the values from a table if they differ in Unit of Measure

    How to retrieve the values from a table if they differ in Unit of Measure?

    If no data is read
    - Insure that you use internal code in SELECT statement, check via SE16 desactivating conversion exit on table T006A. ([ref|http://help.sap.com/saphelp_nw70/helpdata/en/2a/fa0122493111d182b70000e829fbfe/frameset.htm])
    If no quanity in result internal table
    - There is no adqntp field in the internal table, so no quantity is copied in itab ([ref|http://help.sap.com /abapdocu_70/en/ABAPINTO_CLAUSE.htm#&ABAP_ALTERNATIVE_1@1@]).
    - - Remove the CORRESPONDING, so quantity will fill the first field adqntp1.  ([ref|http://help.sap.com/abapdocu_70/en/ABENOPEN_SQL_WA.htm])
    - - Then loop at the internal table and move the quantity when necessary to the 2 other fields.
    * Fill the internal table
    SELECT msehi adqntp
      INTO TABLE internal table
      FROM lipso2
      WHERE vbeln = wrk_doc1
        AND msehi IN ('KL','K15','MT').
    * If required move the read quantity in the appropriate column.
    LOOP AT internal_table ASSIGNING <fs>.
      CASE <fs>-msehi.
        WHEN 'K15'.
          <fs>-adqnt2 = <fs>-adqnt1.
          CLEAR <fs>-adqnt1.
        WHEN 'MT'.
          <fs>-adqnt3 = <fs>-adqnt1.
          CLEAR <fs>-adqnt1.
      ENDCASE.
    ENDLOOP.
    - You could also create another table with only fields msehi and adqntp and then collect ([ref|http://help.sap.com/abapdocu_70/en/ABAPCOLLECT.htm]) the data to another table.
    Regards,
    Raymond

  • How to get the value entered in input enabled field of a list output?

    Hi all,
    I am developing a program to display  list with two input enabled fields . After users enetered the values into these fields I need to do some calculations based on these values and modify the value of another field in the list.
    But i couldn't have an idea how to read the values after users enter into these fields.
    Please help me on solving this problem?  If possible please provide the sample code.
    Thanks,
    Aravind.

    You can enable disable screen fields in at selection screen output event.
    And by using loop at screen.
    And for changing the values you can do in initialization event.
    I Hope you are doing these in Reports.

  • How to delete the values from TKOMV at runtime after creating PO

    Hi,
      How to delete the values from TKOMV at runtime after creating PO from IDOC. I am creating PO through IDOC, subsequently need to create Sales order and again need to create 2nd PO with reference of Purchase Requestion(created with sales order). At the time creation of 2nd PO the Header conditions are appearing twice and net price value is appearing wrong.
    Thanks in advance.

    Hi Padma
    Can you do this activity once the company code is in to production. I guess you can not do this activity, if the company code is already in to live. Setting or resetting of the recon accounts will hinder the previous actitivity. Infact resetting of the company code is also not a good option.
    Any how, thanks for the inputs. Please let me know whether i can do this activity only at the subledger level which will not impact other modules. The one solution i can figured out is , reverse all the transactions for the corresponding asset in the year of takeover and pass the entries again in the same year correctly which will have effect in Subledger and also in general ledger. But the business people will not allow this, since for a big client it will require lot of authorizations and approvals. Infact the vendor also, is cleared. So we have to reverse the cleared documents as well which is again a task and require approvals as well.
    Thanks and regards
    Seshu.

  • How to find the number of users  connected to database from OS level(Linux)

    Hi All,
    Could anyone know , how to find the number of users connected to database without connecting with sql*plus
    is there any command to find it?
    example we have 10 databases in one server, how to find the number of users connected to particular database without connecting to database(v$session)?
    oracle version:- 10g,11g
    Operating System:- OEL4/OEL5/AIX/Solaris
    any help will be appreciated.
    Thanks in advance.
    Thank you.
    Regards,
    Rajesh.

    Excellent.
    Tested, works as long as you set the ORACLE_SID first ( to change databases )
    ps -ef | grep $ORACLE_SID | grep "LOCAL=NO" | awk '{print $2}' | wc -l
    Thanks!
    select OSUSER
        from V$SESSION
    where AUDSID = SYS_CONTEXT('userenv','sessionid')
        and rownum=1;Best Regards
    mseberg

  • How to get the values from html:select? tag..?

    i tried with this, but its not working...
    <html:select styleClass="text" name="querydefs" property="shortcut"
                 onchange="retrieveOptions()" styleId="firstBox" indexed="true">
    <html:options collection="advanced.choices" property="shortcut" labelProperty="label" />
    </html:select>
                        <td align="left" class="rowcolor1">
                        <script language="javascript" type="text/javascript">
                              function retrieveOptions(){
                             var sel = document.querydefs.options;
                             var selectedOption = sel[sel.selectedIndex].value;
                             document.write(selectedOption);
                           </script>

    <td align="left" class="rowcolor1">
                        <script language="javascript" type="text/javascript">
                              function retrieveOptions(){
                             var sel = document.querydefs.options;
                             var selectedOption = sel[sel.selectedIndex].value;
                             document.write(selectedOption);
                           </script>This java script is not working at all..its not printing anything in document.write();
    This is code..
    <td class="rowcolor1" width="20%">
    <html:select styleClass="text" name="querydefs" property="shortcut"
                             onchange="retrieveSecondOptions()" styleId="firstBox"
                             indexed="true">
                             <html:options collection="advanced.choices" property="shortcut"
                                  labelProperty="label"  />
                        </html:select>i tried with this also. but no use..i'm not the getting the seleced option...
    function retrieveOptions(){
    firstBox = document.getElementById('firstBox');
                             if(firstBox.selectedIndex==0){
          return;
        selectedOption = firstBox.options[firstBox.selectedIndex].value;
    }actually , how to get the values from <html:select> ...?
    my idea is to know which value is selected from the combo box(<html:select> ) if that value is equal some string i have enable a hyperlink to open a popup window

  • How to get the values from repeated frame?.

    Hi
    how to get the values from repeated frame?. i have to disply the first 3 digits in another place in my report.
    i have field empno in repeated frame and i want to disply first 3 digits in another place in the same report.
    thanks

    How often do you need to display it? It sounds like you might want to base a summary on that formula with a function of first or last. If it's a per page basis, it can be a page level summary. If it's at a higher level repeating frame, then you can create the summary at that level. I'd suggest taking a look at the online help for summaries using the first/last functions.
    Hope that helps,
    Toby

  • How to move the value from a character field to numeric or packed decimal

    Hi,
    can anyone explain me on how to move the value from a character field to numeric or packed decimal.
    Please help me on this. Thanks...
    Regards,
    Rose.

    Hi ,
    if you use keyword MOVE u may loose the decimal and thoussan separator and if u don't want to loose them just call the FM ..HRCM_STRING_AMOUNT_CONVERT.
    i doubt wherther it is HRCM or HCRM just try using *
    this will suit ur requirement.
    Regards,
    KK

Maybe you are looking for