Stroring data taken from database as a variable

Hi there I;m having a problem and I was wondering if anyone can help me?
I am trying to extract data from a MySQL database and store the variables so I can use them in another bean...
so far I am getting a SQL exception error but I dont know what Im doing wrong.......
My bean code is :
public int getAge(int age) throws SQLException, Exception{
if(con != null){
try{
String userName = null;
ResultSet rs;
Statement stmt = con.createStatement();
rs = stmt.executeQuery("SELECT (age) FROM gymuser WHERE Username='" userName "'");
age = rs.getInt("age");
return age;
} catch(SQLException sqle){
error = "SQLException: could not search gymuser";
throw new SQLException(error);
catch(Exception e){
error = "An exception occured while searching gymuser";
throw new Exception(error);
} else {
error = "Exception: connection to database was lost";
throw new Exception(error);
The JSP that calls this is :
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@page import="java.sql.*, java.io.*, java.util.*;"%>
<jsp:useBean id="details" scope="session" class="fitness.DBQuery" />
<jsp:useBean id="conn" class="fitness.DBConnect" />
<jsp:useBean id="currentuser" scope="session" class="fitness.currentuserBean" />
--%>
<%--
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
--%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GetDetails</title>
</head>
<body>
<h1>GetDetails</h1>
<%
int age = 0;
String userName = currentuser.getName();
conn.connect();
     details.setCon(conn.getCon());
     details.getAge(age);
conn.disconnect();
%>
</body>
</html>
Any help you have to offer would be greatly appreciated as Im desperate!! :-)

Thanks for your help, greatly appreciated....
I havent ever had to use DTO's before as this is the first time in my project where I need t use databasa data as variables in other classes.....so I should have a classthat looks like this ??: /*
* GymUser.java
* Created on 26 April 2007, 13:02
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
package fitness;
import java.sql.*;
import java.io.*;
import java.util.*;
import java.util.Date;
import java.io.Serializable;
* @author Hegstatic
public class GymUser implements Serializable{
    /** Creates a new instance of gymUser */
     private String error;
     private String userName;
     private int age; // + getter + setter
    private double weight;
    private String gender;
    public int getAge(){
         return age;
    public void setAge(int i)
         age = i;
    public double getWeight()
        return weight;
    public void setWeight(double d)
        weight = d;
    public String getGender()
        return gender;
    public void setGender(String string)
        gender = string;
    Connection con;
    private String Frankie;
public GymUser getGymUser()
                 if(con != null){
                 try{
                ResultSet rs;
                Statement stmt = con.createStatement();
               rs = stmt.executeQuery("SELECT * FROM gymuser WHERE Username='" +Frankie+ "'");
                List<GymUser> gymUsers = new ArrayList<GymUser>();
                while (rs.next()) {
                    GymUser gymUser = new GymUser();
                    gymUser.setAge(rs.getInt("age"));
                    gymUser.setWeight(rs.getDouble("weight"));
                    gymUser.setGender(rs.getString("gender"));
                    gymUsers.add(gymUser);
    return gymUsers;
                 } catch(SQLException sqle){
               error = "SQLException: could not search gymuser";
                throw new Exception(error, sqle);
               catch(Exception e){
               error = "An exception occured while searching gymuser";
               throw new Exception(error);
                } else {
               error = "Exception: connection to database was lost";
               throw new Exception(error);
    }The IDE is telling me that the value I have for
return gymUsers; is wrong...
Was just wondering if I am going in the right direction and how would I call the variables age, weight, gender in a JSP page??
Again Thank you !!
Hegtic

Similar Messages

  • Caching data read from database

    I have a big performace problem in our J2EE application. We use jsp and servlets to process a request. Servlet gets the results from database which are stored in a vector of dataobjects and vector is stored in session. We display only 20 rows in jsp and provide page navigation to view more data by Next and Prev links. The problem is we want to store results in request object instead of session variable but then that data is not availabe for Next and Prev links. We don't want to do another search to view more data. Is there a way to cache the data so that while view more data by page navigation we don't need to hit database since request object would be cleared at that time. I am clueless. I hope I explained the problem properly. Any help on this would be highly appreciated

    You're not clueless, you said it yourself.
    To make info available over multiple requests, you need to use a session variable rather than the request.

  • SQL Data Access from database

     Hi Friends,
     I want to access data from database, User will enter Start Date and end date , based on that , data will be get retried.
    Is it possible to write a SQL Query, Where A SQL Query will take care user start and end date. Start date and end date is not fixed, it will be vary based on user.
    Thanks for co-operation.
    Regards,
    Pritam A.

    Pritama,
    Yes, your query looks fine. It should work perfectly. You could alternatively, get input from user into variables and use them in your query as shown below:
    declare @user_startdate datetime
    set @user_startdate='10/Oct/2013 1:00:04'
    declare @user_enddate datetime
    set @user_enddate='14/Oct/2013 1:00:04'
    SELECT * FROM GT1
    WHERE datetime1 BETWEEN @user_startdate AND @user_enddate
    Is there anything else you are facing a problem with? Your query is correct and gives no problems..
    Thanks,
    Jay
    <If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>

  • CRVS2010 beta - Date field from database does not display in report

    Hi there - can someone please help?!
    I am getting a problem where a date field from the database does not display in the report viewer (It displays on my dev machine, but not on the client machines...details given below)
    I upgraded to VS 2010
    I am using the CRVS2010 Beta
    My development machine is Windows 7 - and so is my fellow developer's
    We are using Microsoft SQL Server 2000
    We run the queries within VS and then we send the data table to VS using .SetDataSource
    We have a few reports which display the date on our dev machines (whether we run the EXE or from within Visual Studio)
    When we roll out to the client machines (running Windows XP SP3) then everything works, except that the date does not display (on quite a few reports)
    This is the only real issue I have had - a show stopper for me
    The rest works well - any input will be greatly appreciated
    Regards,
    Ridwan

    Hi Ridwan,
    After much testing I have it all working now using CRDB_adoplus.dll as a data source ( XML )
    Alter your Config file to look like this:
    <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0"/>
    </startup>
    Then using the code below, and CR requires the Schema to be able to read the date format.
    private void SetToXML_Click(object sender, EventArgs e)
    CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
    ISCDReportClientDocument rcd;
    rcd = rptClientDoc;
    string connString = "Provider=SQLOLEDB;Data Source=dwcb12003;Database=xtreme;User ID=sb;Password=password";
    string sqlString = "Select * From Orders";
    OleDbConnection oleConn = new OleDbConnection(connString);
    OleDbDataAdapter oleAdapter = new OleDbDataAdapter(sqlString, oleConn);
    //OleDbDataAdapter oleAdapter2 = new OleDbDataAdapter(sqlString2, oleConn);
    DataTable dt1 = new DataTable("Orders");
    oleAdapter.Fill(dt1);
    System.Data.DataSet ds = new System.Data.DataSet();
    // We need the schema to get the data formats
    ds.WriteXml("c:
    sc.xml", XmlWriteMode.WriteSchema);
    //Create a new Database Table to replace the reports current table.
    CrystalDecisions.ReportAppServer.DataDefModel.Table boTable = new CrystalDecisions.ReportAppServer.DataDefModel.Table();
    //boMainPropertyBag: These hold the attributes of the tables ConnectionInfo object
    PropertyBag boMainPropertyBag = new PropertyBag();
    //boInnerPropertyBag: These hold the attributes for the QE_LogonProperties
    //In the main property bag (boMainPropertyBag)
    PropertyBag boInnerPropertyBag = new PropertyBag();
    //Set the attributes for the boInnerPropertyBag
    boInnerPropertyBag.Add("File Path ", @"C:\sc.xml");
    boInnerPropertyBag.Add("Internal Connection ID", "{680eee31-a16e-4f48-8efa-8765193dccdd}");
    //Set the attributes for the boMainPropertyBag
    boMainPropertyBag.Add("Database DLL", "crdb_adoplus.dll");
    boMainPropertyBag.Add("QE_DatabaseName", "");
    boMainPropertyBag.Add("QE_DatabaseType", "");
    //Add the QE_LogonProperties we set in the boInnerPropertyBag Object
    boMainPropertyBag.Add("QE_LogonProperties", boInnerPropertyBag);
    boMainPropertyBag.Add("QE_ServerDescription", "NewDataSet");
    boMainPropertyBag.Add("QE_SQLDB", "False");
    boMainPropertyBag.Add("SSO Enabled", "False");
    //Create a new ConnectionInfo object
    CrystalDecisions.ReportAppServer.DataDefModel.ConnectionInfo boConnectionInfo =
    new CrystalDecisions.ReportAppServer.DataDefModel.ConnectionInfo();
    //Pass the database properties to a connection info object
    boConnectionInfo.Attributes = boMainPropertyBag;
    //Set the connection kind
    boConnectionInfo.Kind = CrConnectionInfoKindEnum.crConnectionInfoKindCRQE;
    //*EDIT* Set the User Name and Password if required.
    boConnectionInfo.UserName = "";
    boConnectionInfo.Password = "";
    //Pass the connection information to the table
    boTable.ConnectionInfo = boConnectionInfo;
    //Get the Database Tables Collection for your report
    CrystalDecisions.ReportAppServer.DataDefModel.Tables boTables;
    boTables = rptClientDoc.DatabaseController.Database.Tables;
    //For each table in the report:
    // - Set the Table Name properties.
    // - Set the table location in the report to use the new modified table
    boTable.Name = "Orders";
    boTable.QualifiedName = "Orders";
    boTable.Alias = "Orders";
    rptClientDoc.DatabaseController.SetTableLocation(boTables[0], boTable);
    //Verify the database after adding substituting the new table.
    //To ensure that the table updates properly when adding Command tables or Stored Procedures.
    rptClientDoc.VerifyDatabase();
    MessageBox.Show("Data Source Set", "RAS", MessageBoxButtons.OK, MessageBoxIcon.Information);
    Thanks again
    Don

  • Reading Data Clusters from Database ??

    Hi at all,
    how can I read Data from a ClusterTable´`?
    In the Database "STXL" is a field "CLUSTR" and "CLUSTD" and i want see the input. But before i can see it, i must read this Data Cluster.
    How does it work``?
    IMPORT tab = itab
    FROM DATABASE stxl(tx)
    ID   wa_TDOBJECT
    TO wa_stxl.

    well, normally you got FM´s which enable you to do selects or whatever with cluster tables.
    in your case it would be FM READ_TEXT or related FM´s. I do ABAP programming for quite a while now, and i never came to the situation where i manually had needed to read a cluster table.

  • Outbound request data taken from response data?

    Hello,
    In a synchronous scenario, I would like to have some of the outbound request field data also be used in outbound response fields.  These fields do not exist in the inbound message.  Example:
    Outbound Request
    <A>10</A>
    <B>Help</B>
    Inbound Request
    <A>10</A>
    Inbound Response
    <C>50</C>
    Outbound Response
    <B>Help</B>
    <C>50</C>
    Here, the <B> tag's outbound response is taken from that of the inbound request.  Is there a way to do this in XI without persisting outside of the integration engine (such as writing to db or file in the mapping) this value?
    Thanks for any help.

    Hi Bevan,
    u can use a BPM and put that value into a container (don't need multi mapping).
    One other possibility is to give that value to Inbound request - the requested application must give it back - and response.
    Regards,
    Udo

  • How to get Date value from database and display them in a drop down list?

    Hello.
    In my Customers table, I have a column with Date data type. I want to create a form in JSP, where visitors can filter Customers list by year and month.
    All I know is this piece of SQL that is convert the date to the dd-mm-yyyy format:
    SELECT TO_CHAR(reg_date,'dd-mm-yyyy') from CustomersAny ideas of how this filtering possible? In my effort not to sound like a newbie wanting to be spoonfed, you can provide me link to external notes and resources, I'll really appreciate it.
    Thanks,
    Rightbrainer.

    Hi
    What part is your biggest problem?? I am not experienced in getting data out of a database, but the way to get a variable amount of data to show in a drop down menu, i have just messed around with for some time and heres how i solved it... In my app, what i needed was, a initial empty drop down list, and then using input from a text-field, users could add elements to a Vector that was passed to a JComboBox. Heres how.
    package jcombobox;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Vector;
    import javax.swing.*;
    public class Main extends JApplet implements ActionListener {
        private Vector<SomeClass> list = new Vector<SomeClass>();
        private JComboBox dropDownList = new JComboBox(list);
        private JButton addButton = new JButton("add");
        private JButton remove = new JButton("remove");
        private JTextField input = new JTextField(10);
        private JPanel buttons = new JPanel();
        public Main() {
            addButton.addActionListener(this);
            remove.addActionListener(this);
            input.addActionListener(this);
            buttons.setLayout(new FlowLayout());
            buttons.add(addButton);
            buttons.add(remove);
            add(dropDownList, "North");
            add(input, "Center");
            add(buttons, "South");
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == addButton) {
                list.addElement(new SomeClass(input.getText()));
                input.setText("");
            } else if (e.getSource() == remove) {
                int selected = dropDownList.getSelectedIndex();
                dropDownList.removeItemAt(selected);
        public void init(String[] args) {
            setSize(400,300);
            getContentPane().setLayout(new BorderLayout());
            getContentPane().add(new Main());
    }And that "SomeClass" is show here
    package jcombobox;
    public class SomeClass {
        private String text;
        public SomeClass(String input) {
            text = input;
        public String toString() {
            return text;
    }One of the things i struggled a lot with was to get the dropdown menu to show some usefull result. If the list just contains class references it will show the memory code that points to that class. Thats where the toString cones in handy. But it took me some time to figure that one out, a laugh here is welcome as it should have been obvious :-)
    When the app is as simple as this one, using a <String> vector would have been easier, but this is just to demonstrate how to place classes in a vector and get some usefull info out of it, hope this answered some of your question :-)
    The layout might have been easier to write, than using the toppanel created by the JApplet and then the two additional JPanels, but it was just a small app brewed together in 15 minutes. Please comments on my faults, so that i can learn of it.
    If you need any of the code specified more, please let me know. Ill be glad to,

  • How do I get dates pulled from database to display in Spanish?

    I'm pulling a date from a MySQL database and need to have it
    display in Spanish. If it were in English, these are the two
    statements I would be using:
    #DateFormat(event_date,"mmmm")#
    #DateFormat(event_date,"mmm d")#
    I tried using <cfset SetLocale("Spanish (Standard)")>
    in my Application.cfm , but it didn't seem to work. I'm not really
    sure how it is supposed to be used or even if it would work if I
    were using it correctly.
    Any help would be appreciated.
    Thanks -CaddyX

    Bagger Vance wrote:
    > setLocale("es_ES"); // or whatever locale you're using
    for "Spanish"
    > // all the subsequent LS functions will use this locale
    > writeoutput("#lsDateFormat(eventDate,"FULL")#");
    >
    >
    >
    > Paul, Thanks for responding. I'm still not sure how to
    make it work. Do I just
    > put <cfset SetLocale("es_ES")> somewhere in the
    document? That didn't seem to
    > change the result in the following code:
    you can put it at the top of pages that need to be localized
    or better yet in
    your application cfm/cfc.
    >
    <cfoutput>#DateFormat(get_event.event_date,"mmmm")#</cfoutput>
    yes it won't change that, the regular cf functions all use
    en_US locale. you
    want the "LS" functions (re-read the code snippet above).

  • Having problem with adding and reading dates to/from database !!!

    Hi
    I am new in J2ME
    I am trying to code a simple software.
    My problem is with dates.
    I have a datefield on my menu and the user will choose the date from here. By default, datefield shows todays date. But when I try to write that date to database using rms, date value transforms to java.util.Date@acfdb0fe.
    As I read from tutorials this is common problem of date class, so I tried to use calendar class.
    But with Calendar class I cannot let user to choose date from screen like DateField. datefield dowsn't work with calendar.
    later, I will use that date for sorting records
    Summary : I need a sample code that read date from screen (preferably with datefield), write it to recordstore. and then read it from recordstore asnd write to screen.
    I searching internet for a sample code through days.
    Please help me
    Thanks

    Hi,
    The best i would suggest is instead of storing the date as 19 Jan 2004 or something like this better store the date in milliseconds.
    DateField df = new DateField();
    Date d = df.getDate();
    long ms = d.getTime();
    store the value of ms in RMS. This is the commonly used way to store date in RMS for j2me.
    You can get back date using
    Date d = new Date(ms);
    DateField df = new DateField();
    df.setDate(d);
    Prabhu.

  • Implement paging (prev/next) for jtable data obtained from database

    Hello all, first time poster and relative newbie to java.
    I am trying to learn java and in the process have stumbled upon this issue.
    I have searched through the forum as well as googled my way around for answers. And though I am more informed than I was, I still am a little stumped.
    I would like to implement a table that pulls data from a database (mysql), limits the results, and include prev/next buttons to traverse through the records.
    I think this involves writing my own AbstractTableModel. And I have seen some examples as such. But could use a little more help.
    I will always be pulling 10 rows, but the columns will change depending on query I am using so implementing a more generic set of methods would be great.. To be specific...
    Table: users
    Columns: userid, ufname, ulname, utype, ustatus, etc....
    For selection purposes I only need to show: userid, ufname, ulname. So I figure I write a query like:
    select userid, ulname, ufname from users limit index, 10
    Where index tells the query where to start from then use the results to populate the jtable. I can do this statically but do not quite understand how to implement the next/prev buttons so that the table pulls the next or previous set of data.
    If this can happen without the need to repaint/refresh the frame that would be great.
    sudo code (with comments) would be ok, but a basic working example of this would be even better.
    thank you in advance, if more information is required please let me know.

    tumbleweeds roll by...........

  • JSP: Data retrieval from database

    Hi Everyone...
    I know that inorder to extract a value from a database and output to the screen the syntax will be
    <%= rst.getString("DeliveryID")%>.
    But what if I want to extract the value from the database and instead of outputting to the screen, I want to assign it to a variable I have declared.
    I tried the following but it did not work:
    <% String name = request.getString("DeliveryID"); %>.
    I hope someone can help me out in this.
    regards
    BabyJava

    Hi Guys...
    Really thanks for the advice, I guess you guys are right. But it's too late for me to change anything now so I am more or less stuck with the existing design. I have got one new problem though.
    I want to update all values of a table at once and this is the SQL statement I used, but it's not working. I guess the problem could be with the way I am using the wildcard. Here is the code:
    String query = " UPDATE Customer SET CustomerID = '"+CustID +"'," +
                           " CustomerName = '"+CustName+"', CustomerPassword = '"+CustPassword+"', " +
                           " CustomerType = '"+CustType+"' , CustomerAddress = '"+CustAddress+"' ," +
                           " CustomerHandphone = '"+CustHandphone+"'" +
                           " WHERE CustomerID LIKE 'C%' ";
                           I am getting a general error. Is there anything wrong with my code??
    regards
    BabyJava

  • Report Bursting with data fetch from database

    Hi,
    i have a report which needs to be published in the below mentioned way and the report is scheduled daily.
    1. Fetch the details from the database with the Client id, language preference, delivery mechanism(Email,FTP,Fax), delivery location(Email -ID,FTP Location,FAx number).
    2. The client id needs to be passed as a parameter and the report has to be generated in the preferred language and deliver the generated report as per the preference.
    3. The delivery also needs to be tracked accordingly.
    Could you kinldy post your suggestions on the same.
    Thanks,
    Vijay

    The data table is created by me. I am positive that every field in the table has a value for every single record.

  • How to Create a Rich Dynamic Input and Output PDF to insert and get data into, from Database (MSSQL)

    HI ,
    I want to use Adobe LiveCycle Designer and Adobe LiveCycle Workbench features to create a Dynamic PDF form which can allow me to store data into database(MSSQL Server) and Can also provide me the Output PDF form with all the information which has been been filled in by the User in input form. Both Input and Output forms must be Dynamic. I am stuck in this process and Need Experts Advice on the Complete optimal process flow of the Adobe.
    Regards
    Ritesh Grover

    HI
    Go to the lay out of your screen and doublr click on the table control fields, you can get the Properties/Attribute of the screen or table control Fields
    Assing a Group GRP1 for all the fields i n the table control.
    in PBO
    if ok_code = 'INPUT'.
    LOOP AT SCREEN.
    IF screen-grp1 = 'GRP1'.
    screen-input = 1.
    modify screen.
    endif.
    ENDLOOP.
    elseif ok_code = 'OUTPUT'.
    LOOP AT SCREEN.
    if screen-grp1 = 'GRP1'.
    screen-input = 0.
    modify screen.
    endif.
    endloop.
    endif.
    Regards
    Ramchander Rao.K
    Edited by: Ramchander Krishnamraju on Aug 8, 2009 5:27 AM

  • Where is the date taken from when releasing to accounting an invoice

    Hi all,
    I'm using tcode vf02 to release accounting a certain delivery (by pressing the green flag). I have to check why the date - bkpf-bldat is not written correctly.
    Do you know, by any chance where the access to BKPF table is done? The program or line would really be helpfull. I could not find anything by debug.
    Thanks.

    I found the solution and I post it if maybe someone needs it:
    In RV_ACCOUNTING_DOCUMENT_CREATE:
    line 182, bldat is overwritten with vbrk-fkdat
    xaccit-bldat - vbrk-fkdat.
    For other processing of the date, at line 1791 - call customer-function '008'
    userexit_saplv60B_008.

  • JList problems: howto use my own indexes taken from database.

    Hello, I'm new to Java.
    I'm reading names and Unique ID from my employee table. but when selected from listbox I want to get ID of my employee not SelectedIndex of jList is there any ready solution or what can you advice.
    Example:
    ID NAME
    1 Fayziddin Jurayev
    2 Sanjar Sharipov.
    48 Muhammad Jurayev
    49 -----XXXXX================> This record has been deleted
    50 Sanjar Sharipov
    As you see here two person have the same name also looking for person in the table using name will cause mistakes. But if I use SelectedIndex of person in a listbox again I make mistake as 49 th record is deleted.
    I think best solution is to store at the array somewhere NAMES and ID's and use ID to recognize correctly selected person.
    Can someone advice the easiest way to do it(I've used Visual Fox Pro before JAVA)
    Thanks

    Check out this posting:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=608684

Maybe you are looking for