Help with Date objects

          I need to get the current date from within a JSP and insert it into an
          Oracle database.
          I need the form to be DD-MON-YY.
          What is the recommended approach for this? I have been experimenting with
          time conversions and etc.. but it gets to cludgy. There must be an easier
          way.
          Thanks,
          CC
          

See the data formatting classes in java.text ... what you need is there.
          Peace,
          Cameron Purdy
          Tangosol, Inc.
          Clustering Weblogic? You're either using Coherence, or you should be!
          Download a Tangosol Coherence eval today at http://www.tangosol.com/
          "Rhugga" <[email protected]> wrote in message
          news:[email protected]..
          >
          > I need to get the current date from within a JSP and insert it into an
          > Oracle database.
          >
          > I need the form to be DD-MON-YY.
          >
          > What is the recommended approach for this? I have been experimenting with
          > time conversions and etc.. but it gets to cludgy. There must be an easier
          > way.
          >
          > Thanks,
          > CC
          >
          >
          

Similar Messages

  • Need Help with Dates

    I am printing a calendar and certain events will be helds on certain dates.
    One can edit the event if it has not passed the date. Events in the past can be viewed but not edited.
    When I query the database the date must be formatted dd-MMM-yy
    I am able to get today's date by doing this:
    java.util.Date today = new java.util.Date();
    String formatString = "dd-MMM-yy";
    SimpleDateFormat sdf = new SimpleDateFormat(formatString);
    String today_str = sdf.format(today);
    My code for printing the calendar: I left out some of the table formatting in the JSP page.
    GregorianCalendar d = new GregorianCalendar();
    int today = d.get(Calendar.DAY_OF_MONTH);
    int month = d.get(Calendar.MONTH);
    d.set(Calendar.DAY_OF_MONTH,1);
    int weekday = d.get(Calendar.DAY_OF_WEEK);
    for(int i = Calendar.SUNDAY; i < weekday; i++)
    out.print("<td> </td>");
    do {
    int day = d.get(Calendar.DAY_OF_MONTH);
    out.print("<td>" + day + "</td>");
    String formatString = "dd-MMM-yy";
    SimpleDateFormat sdf = new SimpleDateFormat(formatString);
    //if(event exists on this day
    // Get results
    // print link for viewing
    // if (after today) print link for edit
    if(weekday == Calendar.SATURDAY)
    out.println("</tr><tr valign=top>");
    d.add(Calendar.DAY_OF_MONTH,1);
    weekday = d.get(Calendar.DAY_OF_WEEK);
    } while(d.get(Calendar.MONTH) == month);
    if(weekday != Calendar.SUNDAY)
    System.out.println();
    The part I need help on is this:
    //if(event exists on this day
    // Get results
    // print link for viewing
    // if (after today) print link for edit
    I'm looping through each day of the month to print the days. I have the month, day, year as integers. How can I create a date object out of that and compare it to today's date to test if it's before or after today???
    All the function in the Date class that I think would do this have been deprecated.

    Need Help with Dates
    Here is some information about dates:
    There are many edible palm fruits, and one of the most widespread and favored of these is the data (Phoenix dactylifera). Dates were cultivated in ancient land from Mesopotamia to prehistoric Egypt, possibly as early as 6000 B.C. Then--as now--dates were a staple for the natives of those dry regions. Much later, Arabs spread dates around northern Africa, and dates were introduced into California by the Spaniards in 1765, around Mission San Ignacio.
    The date prefers dry, hot climates, because date fruits are injured at temperatures of 20 degrees F, and the damp climate of the California coast was not favorable for fruit production. In the mid-1800s, the date industry developed in California's hot interior valleys and in Arizona. Now the date industry in the United States is localized mostly in the Coachella Valley, where the sandy soils permit the plants to be deeply irrigated. Today the new varieties, mostly introduced in this century, produce about 40 million pounds of dates per annum, or over 60% of the dates consumed in this country. The rest are imported mainly from Persia. According to one survey, about one million people are engaged entirely in date palm cultivation worldwide.
    Hope that helps.

  • Is there a Java utility class to help with data management in a desktop UI?

    Is there a Java utility class to help with data management in a desktop UI?
    I am writing a UI to configure a network device that will be connected to the serial port of the computer while it is being configured. There is no web server or database for my application. The UI has a large number of fields (50+) spread across 16 tabs. I will write the UI in Java FX. It should run inside the browser when launched, and issue commands to the network device through the serial port. A UI has several input fields spread across tabs and one single Submit button. If a field is edited, and the submit button clicked, it issues a command and sends the new datum to the device, retrieves current value and any errors. so if input field has bad data, it is indicated for example, the field has a red border.
    Is there a standard design pattern or Java utility class to accomplish the frequently encountered, 'generic' parts of this scenario? lazy loading, submitting only what fields changed, displaying what fields have errors etc. (I dont want to reinvent the wheel if it is already there). Otherwise I can write such a class and share it back here if it is useful.
    someone recommended JGoodies Bindings for Swing - will this work well and in FX?

    Many thanks for the reply.
    In the servlet create an Arraylist and in th efor
    loop put the insances of the csqabean in this
    ArrayList. Exit the for loop and then add the
    ArrayList as an attribute to the session.I am making the use of Vector and did the same thing as u mentioned.I am using scriplets...
    >
    In the jsp retrieve the array list from the session
    and in a for loop step through the ArrayList
    retrieving each CourseSectionQABean and displaying.
    You can do this in a scriptlet but should also check
    out the jstl tags.I am able to remove this problem.Thanks again for the suggestion.
    AS

  • Need Help with data type conversion

    Hello People,
    I am new to java, i need some help with data type conversion:
    I have variable(string) storing IP Address
    IPAddr="10.10.103.10"
    I have to call a library function which passes IP Address and does something and returns me a value.
    The problem I have is that external function call in this library excepts IP Address in form of a byte array.
    Here is the syntax for the function I am calling through my program
    int createDevice (byte[] ipAddress).
    now my problem is I don't know how to convert the string  IPAddr variable into a byte[] ipAddress to pass it through method.

    Class InetAddress has a method
    byte[]      getAddress() You can create an instance using the static method getByName() providing the IP address string as argument.

  • Help with date validation on input boxes.

    I need some help with date validation on input boxes.
    What I�m trying to create is a form where a user inputs dates and then the rest of the form calculates the other dates for them.
    i.e. � A user inputs 2 dates (A & B) and then a 3rd date which is 11 weeks before date B is calculated automatically.
    Is this possible and if so how do I do it ???
    Thanks

    Hi,
    to get third date try this:
    java.util.Date bDate = ...;
    Calendar yourCalendar = new GregorianCalendar();
    yourCalendar.setTime(bDate);
    yourCalendar.roll(Calendar.WEEK_OF_YEAR, -11);
    java.util.Date cDate = yourCalendar.getTime();Regards
    Ldinka

  • Need some help with date

    Hi everyone!
    I have an application in Flex AIR and I'm having problems with dates, I could't found an example on internet until now.
    I tried this for insert (database is embeded sqlite)
    insertManager.parameters[":mydate"] = mydate.selectedDate.time; // type of this column is INTEGER (in my table) and store a number (milliseconds from 1/1/1970) ex: 1265079600000
    Then when I need read records
    mydate.selectedDate = new Date(mydateprice); //it supposed show me DD/MM/YYYY but in every case display 1/1/1970
    If I replace mydateprice for mydate.selectedDate = new Date(1265079600000); // it brings me the right date
    So I don't know what happed, and I'm not sure if it's the best idea to store a date in Flex AIR
    I'll appreciate any help, information or example to find a solution.
    Regards!
    Mara.-

    Thank you so much VIKASH!!! it works!!!
    Now I'm trying to format this value 1265079600000 in my datagrid column:
    <mx:DateFormatter id="dateFormatter" formatString="DD/MM/YYYY"/>
    <mx:DataGridColumn width="140" textAlign="left" headerText="DATE" dataField="myDateColumn" labelFunction="formatDate"  />
    public function formatDate(item:Object,column:DataGridColumn):String
    return dateFormatter.format(item.myDateColumn);
    but this column appear empty....
    Regards and thanks again!
    Mara.-

  • Problem with Date objects

    I have a problem when using Date objects. If i create a Date object like this:
    Date d = new Date( 2002,03,20,19,45 ), and i try to get the number of Milliseconds
    ( d.getTime() ) i get a number that cannot be correct. I't is to high. I't looks like i
    get the number of Milliseconds to year 3000+ ?? But if i write out the Date object
    using a DateFormat.getInstance(), the date is equal to the date i entered above!
    Can anybody help me with this ?? Please ??

    Hi... as far as I remember, the getTime method returns the number of milliseconds since January 1 1970 (a holdover from Unix days).

  • Help with date's comparisons

    Know it may be elementary to you .
    I have jobs scheduled with dbms scheduler and want to find out for a job, how long since LAST_START_DATE in HOURS:
    Tried some with to_char etc, did not get the results.
    TIA
    SQL>  SELECT LAST_START_DATE ,job_name from dba_scheduler_jobs where owner='OSI';
    LAST_START_DATE
    JOB_NAME
    27-OCT-13 03.31.07.078895 PM +00:00
    OSIA
    SQL>  SELECT sysdate - LAST_START_DATE ,job_name from dba_scheduler_jobs where owner='OSI';
    SYSDATE-LAST_START_DATE
    JOB_NAME
    +000000000 00:46:15.921105
    OSIA

    Well first off you have your string mixed up, month comes
    before date. So that should be
    var isToday:String = thisDate.getMonth().toString() + "/" +
    thisDate.getDate().toString() + "/" +
    thisDate.getFullYear().toString();
    Then the second thing to take note of is something straight
    out of the live docs with the month.
    month : Number
    The month (0 for January, 1 for February, and so on) portion
    of a Date object according to local time.
    They start at 0 not 1. So you have two options either always
    add one to the month for the correct month if showing the number
    like that or format the date using a DateFormatter before you alert
    it. Which could be done like so.
    var df:DateFormatter = new DateFormatter();
    df.formatString = "MM/DD/YYYY";
    Alert.show(df.format(new Date()), "Full Date");
    Hope this helps.

  • Help with date formatting.

    Hi,
    I have been asked to fix a problem with a report. I have found that the problem is the date format being passed to the stored procedure is not correct, The current format is like Mon April 04 2007. The correct format should be DD-MMM-YYYY which I take to be Mon Apr 04 2004. I am not sure if this is correct anyway, but after looking at the code and the api I have managed to create a date object and call toString on it, after setting a simple date format to dd MMM yyyy.
    The problem is that the toString method returns Mon Apr 02 00:00:00 BST 20
    07. Is anybody able to help me with this? Below is a little bit of the code:
    public void renderDailyReport(ServletWriter out, HttpServletRequest request) throws Exception {
            // reset counters
            totalHits    = 0;
            maxHits      = 0;
            minHits      = 0;
            // get a GregorianCalendar object using the startDate and endDate Strings
            SimpleDateFormat  sdf         = new SimpleDateFormat("dd MMMM yyyy", Locale.UK);
            SimpleDateFormat procedureDateFormat = new SimpleDateFormat("dd MMM yyyy", Locale.UK);
            GregorianCalendar dateCounter = new GregorianCalendar();
            GregorianCalendar upperLimit  = new GregorianCalendar();
            sdf.setCalendar(Calendar.getInstance());
            Date sd = sdf.parse(startDate);
            Date ed = sdf.parse(endDate);
            procStartDate = procedureDateFormat.parse(startDate);
            procEndDate = procedureDateFormat.parse(endDate);The procStart and end dates are the bits that I added.
    They are passed to the stored procedure calling .toString, they are date objects.
    Appreciate any help.

    Do not use the toString() method of Date - it will always be the same format.
    Use the format() method of SimpleDateFormat.
    Date d = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("'dd-MMM-yyyy"); // or something like this
    String s = sdf.format(d);Message was edited by:
    jbish

  • Help with Data Matrix (2D) barcode

    Hey everybody,
    I need a little help with creating a dynamic Data Matrix barcode. The DM Studio help files explain the barcode, regions, data code words, etc, but don't really help with implementation of one. I can create a static one using the actual Barcode widget in DM Studio, but I'm unsure how to create a dynamic one. Minimally I'd need to change the barcode's content from document to document, but if you use the barcode object in your section, it doesn't appear as though it allows variables or variable information (i.e. DAL script results). We have 3 of 9 barcodes, but we create those by simply using the 3of9 font when outputting the barcode's content. With the Data Matrix barcode, that doesn't seem like the appropriate course of action because of additional attributes like Scale or Symbol Size.
    Thanks,
    Gregg

    Hi Gregg,
    I would request you to try like this.
    1. First insert a normal field (not a bar code).
    2. Change 'Type' to Barcode.
    3. Change 'Format' to Data Matrix.
    4. Change 'Length' to 11.
    5. Change Symbol size, Scale appropriately.
    6. Use Rule as usual you would do for a normal field.
    7. Use Data Matrix bar code fonts (13504, 13505, or 13506) which are included with Documaker. If you have any other specific font for Data Matrix bar code, you may try that as well.
    These steps should allow you get a dynamic bar code.
    Thank you.

  • Problems with Date objects

    I want to use the HttpSession.getCreationTime() value and write it to an Oracle Date field.
    I am having trouble getting the value in the proper type and format.
    I have a test servlet to try to understand the various ways to use and convert DateTime values.
    Here's the code:
    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
    long logontime = session.getCreationTime();
    SimpleDateFormat formatter = new SimpleDateFormat("mm-dd-yyy hh:mm:ss");
    java.sql.Date sqlDate = new java.sql.Date(logontime);
    String sDate = formatter.format(sqlDate);
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("DateTime in Milliseconds: " + session.getCreationTime() + "<br>");
    out.println("DateTime as java.sql.Date: " + sqlDate + "<br>");
    out.println("java.sql.Date SimpleDateFormat: " sDate "<br>");
    out.println("</body>");
    out.println("</html>");
    out.close();
    Here's the output:
    DateTime in Milliseconds: 1016812138284
    DateTime as java.sql.Date: 2002-03-22
    java.sql.Date SimpleDateFormat: 48-22-2002 10:48:58
    What's happening with the Month in the SimpleDateFormat output?
    Also,
    How can I convert this string into a valid Date Object to use in CallableStatement.setDate(int index, Date x)?
    Thank you for your help.

    If you have a String that's in that format, and you want to convert it to a java.util.Date, you do something like this:SimpleDateFormat dateFormatter = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
    java.util.Date date = dateFormatter.parse(thatString);Then if you want to convert that to a java.sql.Date, you do this:java.sql.Date sqlDate = new java.sql.Date(date.getTime());However, I suggest you don't actually want to do that. If your date has hours, minutes, and seconds in it then converting to java.sql.Date throws away that information. You may want java.sql.Timestamp instead.

  • Help with dates

    Hello Everybody.
    I need help with de management of dates in my sentence.
    I execute the setence to extract information by dates range.
    but i have a problem, because i need extract the information automatically, the first day of every month.
    the information must be the all last month.
    I dont know, what sentence use.
    The objective is: refresh the date automatically every month.
    This is an example of my sentence, but I need use the field AF_DATE too because this is of date of of production form my information:
    The field af_dat is char.
    WHERE EFM='F' AND AF_DAT BETWEEN 'date1' AND 'date2'
    AND TO_CHAR(AF_TIM,'HH24:MI:SS') BETWEEN
    '05:30:00' AND '23:59:59' OR
    AF_DAT BETWEEN 'date1' AND 'date2'
    AND TO_CHAR(AF_TIM,'HH24:MI:SS') BETWEEN
    '00:00:00' AND '00:45:00'AND EFM='F'
    ORDER BY AF_DAT,AF_TIM;
    Edited by: user10827532 on Jan 23, 2009 7:07 AM

    Hi,
    It looks like you're using two columns, af_dat for the year-month-day, and af_tim for the hours-minutes-seconds.
    A lot of folks would just use one column, and do the kind of range check you want like this:
    WHERE   af_dat_tim >= TRUNC (ADD_MONTHS (SYSDATE, -1), 'MM')   -- Start of LAST month
    AND     af_dat_tim <  TRUNC (            SYSDATE,      'MM')   -- Start of THIS month
    AND     TO_CHAR (af_dt_tm, 'HH24:MI')  NOT BETWEEN  '00:46'
                                               AND      '05:29'

  • Help with date code

    Sry about this amount of code lines.... but i realy need help...
    I must insert into a table, the date, like 10/12/2009, and the time, like 22:34:12... but, when i select the date from a datepicker, and insert the time into a text field... i got this result:
    if the date inserted was 12/12/2009 and the time 22:34:12
    result is.......................12/12/0922 34:12:00 <<<<< it´s getting just the two lasts number of the year and inserting the two firsts number of the time into the year, like year 0922 ....
    I´m using a javascript source to create a datepicker......
    and that is the procedure to insert into the table.......
    PROCEDURE set_atendimento(
    p_id_chamado_atendimento IN chamado_atendimento.id_chamado_atendimento%TYPE,
    p_id_chamado IN chamado_atendimento.id_chamado%TYPE,
    p_informacao IN chamado_atendimento.informacao%TYPE,
    p_datahora_inicio IN chamado_atendimento.datahora_inicio%TYPE,
    p_datahora_fim IN chamado_atendimento.datahora_fim%TYPE,
    p_hora_inicio IN VARCHAR2,
    p_hora_fim IN VARCHAR2
    IS
    v_inicio DATE;
    v_fim DATE;
    BEGIN
    v_inicio := TO_DATE(TO_CHAR(p_datahora_inicio || p_hora_inicio), 'DD/MM/YYYY HH24:MI:SS');
    v_fim := TO_DATE(TO_CHAR(p_datahora_fim || p_hora_fim), 'DD/MM/YYYY HH24:MI:SS');
    UPDATE
    chamado_atendimento
    SET
    informacao = UPPER(p_informacao)
    WHERE
    id_chamado_atendimento = p_id_chamado_atendimento;
    IF SQL%NOTFOUND THEN
    INSERT INTO
    chamado_atendimento
    (id_chamado_atendimento, id_chamado, id_operador, datahora_inicio, datahora_fim, informacao)
    VALUES
    (SEQ_CHAMADO_ATENDIMENTO.nextval, p_id_chamado, pkg_operador.get_id_operador, v_inicio, v_fim, UPPER(p_informacao));
    END IF;
    END;
    that is the JAVASCRIPT
    <script language="JavaScript" type="text/JavaScript">
    $(function(){
    $.datepicker.setDefaults({
    showOn: 'button',
    buttonImage: '/i/themes/fwsac/includes/jquery/images/calendario.gif',
    buttonImageOnly: true,
    closeText: 'Fechar',
    prevText: '<Anterior',
    nextText: 'Pr&oacute;ximo>',
    currentText: 'Hoje',
    monthNames: ['Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
    monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
    dayNames: ['Domingo','Segunda-feira','Ter&ccedil;a-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sabado'],
    dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
    dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
    dateFormat: 'dd/mm/yy',
    firstDay: 0,
    isRTL: false,
    showAnim: 'slide'
    $('#P5004_DATAHORA_INICIO , #P5004_DATAHORA_FIM').datepicker({ beforeShow: fdateRange });
    function fdateRange(input){
    return {
    minDate: (input.id == "P5004_DATAHORA_FIM" ? $("#P5004_DATAHORA_INICIO").datepicker("getDate") : null),
    maxDate: (input.id == "P5004_DATAHORA_INICIO" ? $("#P5004_DATAHORA_FIM").datepicker("getDate") : null)
    </script>
    what i must change to get the 4 numbers of the year and all numbers of the time and conca " || " with the date??
    can someone help with this, pls??

    Hello brugo,
    Try this:
    v_inicio := to_nchar((to_date(p_datahora_inicio || p_hora_inicio , 'DD/MM/YYYY HH24:MI:SS')), 'DD/MM/YYYY HH24:MI:SS');
    v_inicio := to_nchar((to_date(p_datahora_fim || p_hora_fim , 'DD/MM/YYYY HH24:MI:SS')), 'DD/MM/YYYY HH24:MI:SS');When I substitute strings: '10/12/2009' for p_datahora_inicio and '22:30:05' for p_hora_inicio, using this format string, I get: 10/12/2009 22:30:05 as a result.
    Don.
    You can reward this reply by marking it as either Helpful or Correct :)

  • Help with data load model

    Hi,
    I need help with a data load model. First, i'm doing delta extraction from R/3, we load data with a InfoSource to InfoCube A and InfoCube B.
    I'm doing master data validation on the load, so if a load fails for InfoCube A, it fails for InfoCube B too (this is because i can have only 1 InfoPackage for the 2 infocubes, because of the delta update).
    So i propose a new model in wich:
    - The delta load is taked first to an ODS.
    - ODS is cleaned before the delta update.
    - Then i create 2 InfoPackages for full load from ODS to  Infocube A, and from ODS to InfoCube B.
    With this solution i can have 2 infopackages from ODS because i'm not doing a delta load from here to the cubes, and with 2 infopackages i can have independent validations for each cube so if one of them fails, the other can still be loaded sucessfully.
    The solution fails because if i load delta from R/3 to the ODS i can't clean it first. The initialization and the old updates needs to be previuslly loaded on the ODS. Then i can't do full load to the cubes and neither have 2 infopackages.
    Please help me to solve this issue.
    thanks a lot

    Hi jeremy,
    what about this simple solution:
    load data by delta from R/3 in your ODS. You can also have an ODS/cube for the historical data which is more space-saving than holding all the old data in PSA. Then you load your historical data from PSA into the historical ODS/cube.
    From your ODS with the actual data you update your requests by full from ODS into the cubes with 2 different full infopackages. But because you load by full you have to use deletion selections in the infopackages to avoid duplicate data!
    regards,
    Jürgen

  • Problem with Date object in Servlet

    in following code what i want to do is to convert database date field date
    string in to Date format oject. here user entered date string is convered to Date object successfully but database date field date String is not converting to Date object and i want to compare two dates wheter user ented date is more than the database date field. Pls if u can correct this it is a big help for me.
    Thank u,
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.util.Date;
    //import java.text.*;
    public class chkAvail extends HttpServlet
         Connection con=null;
         PreparedStatement ps1,ps2;
         PrintWriter out;
         String UArraDate="";
         String UDepaDate="";
         String ChkType="";     
         Date d2;
    String aDate="";
         public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
              d2=new Date();
              try
                   res.setContentType("text/html");
                   out=res.getWriter();
                   //UArraDate=req.getParameter("ArrDate");
                   //UDepaDate=req.getParameter("DepaDate");
                   //ChkType=req.getParameter("ChkType");
                   String mydb="jdbc:odbc:portal";
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   con=DriverManager.getConnection(mydb);
                   UArraDate="13/09/05";
                   Date d1=new Date(UArraDate);
                   ps1=con.prepareStatement("SELECT * FROM cottageReservation");
                   ResultSet re1=ps1.executeQuery();
                   while(re1.next())
                        //aDate=re1.getString("ADate");
                        //d2=java.sql.Date.valueOf(re1.getString("ADate"));
                        //out.println(d2);
                        aDate=re1.getString("ADate");
                        d2=new Date(aDate);
                        if(d1.after(d2))
                             System.out.println("OK");
                        else
                             System.out.println("NotOK");
              catch(SQLException e)
                   System.out.println(""+e);
              catch(ClassNotFoundException e)
              catch(Exception e)
    }

    Here is an example of how objects can be refered.....
    have a look
    //////////////////////////CustomDatumExample.java///////////////////////////////
    import java.sql.*;
    import oracle.jdbc.driver.*;
    import oracle.sql.*;
    import java.math.BigDecimal;
    public class CustomDatumExample
    /* Example invocation:
    java customDatumTest "jdbc:oracle:oci8:@" SCOTT TIGER \
    "oracle.jdbc.driver.OracleDriver"
    public static void main(String args []) throws Exception
    // Connect
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver ());
    OracleConnection conn = (OracleConnection)
    DriverManager.getConnection("jdbc:oracle:oci8:@",
    "scott", "tiger");
    // Create a Statement
    Statement stmt = conn.createStatement ();
    try
    stmt.execute ("drop table EMPLOYEE_TABLE");
    stmt.execute ("drop type EMPLOYEE");
    catch (SQLException e)
    // An error is raised if the table/type does not exist. Just ignore it.
    // Create and populate tables
    stmt.execute ("CREATE TYPE EMPLOYEE AS OBJECT(EmpName VARCHAR2(50),EmpNo INTEGER)");
    stmt.execute ("CREATE TABLE EMPLOYEE_TABLE (ATTR1 EMPLOYEE)");
    stmt.execute ("INSERT INTO EMPLOYEE_TABLE VALUES (EMPLOYEE('Susan Smith', 123))");
    stmt.close();
    // Create a CustomDatum object
    Employee e = new Employee("George Jones", new BigDecimal("456"));
    // Insert the CustomDatum object
    PreparedStatement pstmt
    = conn.prepareStatement ("insert into employee_table values (?)");
    pstmt.setObject(1, e, OracleTypes.STRUCT);
    pstmt.executeQuery();
    System.out.println("insert done");
    pstmt.close();
    // Select now
    Statement s = conn.createStatement();
    OracleResultSet rs = (OracleResultSet)
    s.executeQuery("select * from employee_table");
    while(rs.next())
    Employee ee = (Employee) rs.getCustomDatum(1, Employee.getFactory());
    System.out.println("EmpName: " + ee.empName + " EmpNo: " + ee.empNo);
    rs.close();
    s.close();
    if (conn != null)
    conn.close();
    /////////////////////////////////////////////////Employee.java///////////////////////////////////
    import java.math.BigDecimal;
    import java.sql.SQLException;
    import oracle.jdbc.driver.OracleConnection;
    import oracle.sql.*;
    public class Employee implements CustomDatum, CustomDatumFactory
    static final Employee _employeeFactory = new Employee(null, null);
    public static CustomDatumFactory getFactory()
    return _employeeFactory;
    public Employee ()
    /* constructor */
    public Employee(String empName, BigDecimal empNo)
    this.empName = empName;
    this.empNo = empNo;
    /* CustomDatum interface */
    public Datum toDatum(OracleConnection c) throws SQLException
    StructDescriptor sd =
    StructDescriptor.createDescriptor("SCOTT.EMPLOYEE", c);
    Object [] attributes = { empName, empNo };
    return new STRUCT(sd, c, attributes);
    /* CustomDatumFactory interface */
    public CustomDatum create(Datum d, int sqlType) throws SQLException
    if (d == null) return null;
    Object [] attributes = ((STRUCT) d).getAttributes();
    return new Employee((String) attributes[0],
    (BigDecimal) attributes[1]);
    /* fields */
    public String empName;
    public BigDecimal empNo;
    }

Maybe you are looking for

  • To many undo redo button

    Hi to everyone!!! I need your advice for my problem!! when I cliked new in the file to create a new JTextPane the undo redo button will multiply and if I have so many JTextPane then I have many undo redo in my toolbar here is my code. import java.awt

  • 100% CPU usage, causes background music to stutter//pause

    Hey, I asked this question before but didn't find the answer I was looking for. This issue happens when drawing with the brush (before lifting my wacom pen for the lines to get optimized) or any action where calculations are being made (like skewing)

  • Can't Access Windows 7 Partition after updating OSX to 10.8.2 - Will I be able to get my data back?

    Itys does not appear in the boot list after holding down alt.  I can still see it in disk utilities as a 66GB partition but it can't be veriefied or repaired from there.  Any assistance in this matter would be greatly appreciated.

  • Newb deserving assistance with Adobe Javascript (check boxes and combo boxes)

    Hi, I'm a newb when it comes to javascript (using adobe acrobat pro 6.0). I am working on a form that will allow me to autofill checkboxes based off of information chosen. Ideally, I would like to have a selection from a combo box autofill/auto check

  • Unable to open files from Finder

    I just bought my Macbook Pro yesterday.  This is my first Mac so bear with me.  I bought and installed Office for Mac.  The problem is that I cannot open files directly from Finder or the folder stack on my Dock.  If I trt to open a Word or Excel fil