jdbc_doc03

download jdbc_doc03

of 17

Transcript of jdbc_doc03

  • 8/11/2019 jdbc_doc03

    1/17

    BLOBs and CLOBs: Storing large fields in a table with the other datais not necessarily the optimum place especially if the data has a

    variable size. One way to handle large, variable sized objects is withthe Large Objects (LOs! type. LOs use a locator, essentially a

    pointer, in the database record that points to the real database field.

    "here are two types of LOs: inary Large Objects (LOs! and#haracter Large Objects (#LOs!. $hen you access a LO or #LO,

    the data is not copied to the client. "o retrieve the actual data from a

    result set, you have to retrieve the pointer with a call to BLOB

    blob=getBlob(1)or CLOB clob=getClob(1), and then retrieve the data with

    a call to blob.getBinaryStream()or clob.getBinaryStream().

    y default, % statements are processed in full auto'commit mode.

    Storing Classes, Images and Other Large Objects

    any databases can store binary data as part of a row if the database

    field is assigned a long raw, longvarbinary, or other similar type. "hese

    fields can accommodate up to two )igabytes of data. "his means if

    you can convert the data into a binary stream or array of bytes, it canbe stored and retrieved from the database in the same way you would

    store a string or double.

    "his techni*ue can be used to store and retrieve images and %ava

    objects.

    Storing and retrieving an image: +t is very easy to store an object

    that can be serialized or converted to a byte array. nfortunately,

    java.awt.Imageis not Serializable. -owever, as shown in this net code

    eample, you can store the image data to a file and store the theinformation in the file as bytes in a database binary field.

    int itemnumber=44!"#

    $ile %ile = new $ile(itemnumber&'.jg')#

    $ileInutStream %i = new $ileInutStream(%ile)# *reare+Statement tmt = con.reareStatement('u+ate auctionitemet t,eimage=- w,ere i+= -')#

    tmt.etBinaryStream(1 %i (int)%ile.lengt,())/ tmt.etInt(0 itemnumber)# tmt.eecute2+ate()# tmt.cloe()# %i.cloe()#

  • 8/11/2019 jdbc_doc03

    2/17

    "o retrieve this image and create a byte array that can be passed to

    createImage, do the following:int itemnumber=44!"#

    byte3 imageByte#*reare+Statement tmt = con.reareStatement(

    'elect t,eimage %rom auctionitem w,ere i+= -')# tmt.etInt(1 itemnumber)# 5eultSet r=tmt.eecute6uery()# i%(r.net()) 7 imageByte = r.getByte(1)# 8 tmt.cloe()# r.cloe()#

    Image auctionimage =9ool:it.get;e%ault9ool:it().createImage( imageByte)#

    Storing and retrieving an object: / class can be serialized to abinary database field in much the same way as the image was in theprevious eample. +n this eample, the 5egitrationImlclass is

    changed to support default serialization by adding imlement

    Serializableto the #lass declaration.

    0et, a Byte

  • 8/11/2019 jdbc_doc03

    3/17

    reg.balance = balance#

    Bytecetion ignore) 7 8 8 8

    "he object is retrieved and reconstructed by etracting the bytes fromthe database, creating a Byte

  • 8/11/2019 jdbc_doc03

    4/17

    i% (: == null) 7 t,row new $in+er>cetion ()# 8 Connection con = null# *reare+Statement = null# try 7 con=getConnection()# =con.reareStatement('

    elect t,ecla %romregitration w,ere t,euer = -')#

    .etString(1 :.t,euer())# .eecute6uery()# 5eultSet r = .get5eultSet()# i%(r.net())7 byte3 regByte = r.getByte(1)# Bytecetion ignore) 78 8 8

    BLOBs and CLOBs: Storing large fields in a table with the other datais not necessarily the optimum place especially if the data has a

    variable size. One way to handle large, variable sized objects is with

    the Large Objects (LOs! type. LOs use a locator, essentially apointer, in the database record that points to the real database field.

    "here are two types of LOs: inary Large Objects (LOs! and#haracter Large Objects (#LOs!. $hen you access a LO or #LO,

    the data is not copied to the client. "o retrieve the actual data from a

    result set, you have to retrieve the pointer with a call to BLOB

  • 8/11/2019 jdbc_doc03

    5/17

    blob=getBlob(1)or CLOB clob=getClob(1), and then retrieve the data with

    a call to blob.getBinaryStream()or clob.getBinaryStream().

    Controlling Transactions

    y default, % statements are processed in full auto'commit mode."his mode wor1s well for a single database *uery, but if an operation

    depends on several database statements that all have to completesuccessfully or the entire operation is cancelled, a finer transaction is

    needed.

    / description of transaction isolation levels is covered in more detail in#hapter 2: &ata and "ransaction anagement. "o use transaction

    management in the % platform, you first need to disable the full

    auto'commit mode by calling:

    Connection con= getConnection()# con.et

  • 8/11/2019 jdbc_doc03

    6/17

    8 Calen+ar currenttime=Calen+ar.getIntance()# java.util.;ate current+ate=currenttime.get9ime()# tart+ate=new java.@l.;ate( current+ate.get9ime())# currenttime.a++(Calen+ar.; auction+ay)# en++ate=new java.@l.;ate((

    currenttime.get9ime()).get9ime())#

    =con.reareStatement( 'inert into auctionitem(

    i+ +ecrition tart+ate en++atetartrice ummary)value (------)')#

    .etInt(1 count)# .etString(0 +ecrition)# .et;ate(A tart+ate)# .et;ate(4 en++ate)# .et;ouble(! tartrice)# .etString(" ummary)#

    .eecute2+ate()# .cloe()#

    =con.reareStatement('u+ate regitrationet balance=balance .!w,ere t,euer= -')#

    .etString(1 eller)# .cloe()# tmt= con.createStatement()# tmt.eecute6uery(

    'elect balance %rom regitrationw,ere t,euer='&eller&'')#

    r = tmt.get5eultSet()# i%(r.net()) 7 balance=r.get;ouble(1)# 8 tmt.cloe()# i%(balance D) 7 con.rollbac:()# con.cloe()# return (1)# 8

    tmt= con.createStatement()# tmt.eecute2+ate(

    'u+ate auctionitem et

    counter=counter&1')# tmt.cloe()# con.commit()# con.cloe()# return()# 8 catc,(S6L>cetion e) 7 try 7 con.rollbac:()# con.cloe()# tmt.cloe()#

  • 8/11/2019 jdbc_doc03

    7/17

    .cloe()# 8catc, (>cetion ignore)78 8 return ()# 8

    Escaping Characters

    "he % /5+ provides the ecae1eyword so you can specify the

    character you want to use to escape characters. 6or eample, if you

    want to use the percent sign (E! as the percent sign and not have it

    interpreted as the S7L wildcard used in S7L LI>*ueries, you have to

    escape it with the escape character you specify with the ecae

    1eyword.

    "his net statements shows how you would use the ecae1eyword to

    loo1 for the value 1E.tmt.eecute6uery(

    'elect ta %rom ale w,ere ta li:e1FE 7ecae F8')#

    +f your program stores names and addresses to the database entered

    from the command line or by way of a user interface, the single *uotes(! symbol might appear in the data. 5assing single *uotes directly into

    a S7L string causes problems when the S7L statement is parsedbecause S7L gives this symbol another meaning unless it is escaped.

    "o solve this problem, the following method escapes any symbol

    found in the input line. "his method can be etended to escape any

    other characters such as commas that the database or database

    driver might interpret another way.

    tatic ublic String ecaeLine(String ) 7 String retvalue = # i% (.in+eO% ('') ?= 1 ) 7 StringBu%%er ,ol+ = new StringBu%%er()# c,ar c# %or(int i=# i D .lengt,()# i&& ) 7 i% ((c=.c,ar

  • 8/11/2019 jdbc_doc03

    8/17

    -owever, if you use a *reare+Statementinstead of a simple Statement,

    most of these escape problems go away. 6or eample, instead of this

    line with the escape se*uence:tmt.eecute6uery('elect ta %rom ale w,ere ta li:e

    1FE 7ecae F8')#

    8ou could use this line:reare+tmt = C.reareStatement( 'u+ate ta et ta = -')#

    Mapping Database Types

    /part from a few % types such as IG9>H>5that are represented as

    an IG9>H>5in most popular databases, you might find that the %

    type for a table column does not match the type as it is represented inthe database. "his means calls to 5eultSet.getObject,

    *reare+Statement.etObjectand CallableStatement.getObject()will veryli1ely fail.

    8our program can determine the database column type from thedatabase meta data and use that information to chec1 the value before

    retrieving it. "his net code chec1s that the value is in fact type

    IG9>H>5before retrieving its value.

    int count=# Connection con=getConnection()# Statement tmt= con.createStatement()# tmt.eecute6uery(

    'elect counter %rom auctionitem')# 5eultSet r = tmt.get5eultSet()# i%(r.net()) 7 i%(r.geteta;ata().getColumn9ye(1) ==

    9ye.IG9>H>5) 7 Integer i=(Integer)r.getObject(1)# count=i.intJalue()# 8 8 r.cloe()#

    Mapping Date types

    "he ;type is where most mismatches occur. "his is because the

    java.util.;ateclass represents both &ate and "ime, but S7L has the

    following three types to represent data and time information:

    / ;type that represents the date only (92;2 / 9I>type that specifies the time only (=;:92:>

    / 9I>S9

  • 8/11/2019 jdbc_doc03

    9/17

    "hese three additional types are provided in the java.@lpac1age as

    java.@l.;ate, [email protected] [email protected] are all

    subclasses of java.util.;ate. "his means you can use convert

    java.util.;atevalues to the type you need to be compatible with the

    database type.

    ote!"he 9imetamclass loses precision when it is

    converted to a java.util.;atebecause java.util.;atedoes

    not contain a nanosecond field, it is better to not convert a

    9imetaminstance if the value will be written bac1 to the

    database.

    "his eample uses the java.@l.;ateclass to convert the java.util.;ate

    value returned by the call to Calen+ar.get9imeto a java.@l.;ate.

    Calen+ar currenttime=Calen+ar.getIntance()# java.@l.;ate tart+ate= new java.@l.;ate(( currenttime.get9ime()).get9ime())#

    8ou can also use the java.tet.Simle;ate$ormatclass to do the

    conversion. "his eample uses the java.tet.Simle;ate$ormatclass to

    convert a java.util.;ateobject to a java.@l.;ateobject:

    Simle;ate$ormat temlate =new Simle;ate$ormat('yyyy++')#

    java.util.;ate en++ate =new java.util.;ate('1KA1K')#

    java.@l.;ate @l;ate =java.@l.;ate.valueO%( temlate.%ormat(en++ate))#

    +f you find a database date representation cannot be mapped to a %ava

    type with a call to getObjector get;ate, retrieve the value with a call to

    getStringand format the string as a ;atevalue using the

    Simle;ate$ormatclass shown above.

    What is JServer and what is it used for?

    Oracle JServer Option is a Java Virtual Machine (Java VM) which runs within the Oracle database server'saddress space. Oracle also provides a JServer Accelerator to compile Java code natively. This speeds up theeecution o! Java code by eliminatin" interpreter overhead.

    #ac$ to top o! !ile

    http://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.orafaq.com/faqjdbc.htm#TopOfFile
  • 8/11/2019 jdbc_doc03

    10/17

    How does one install the Oracle JServer Option?

    %ollow these steps to activate the Oracle JServer& JVM option

    Ma$e sure your database is started with lar"e avapoolsi*e (+,-M) and sharedpoolsi*e

    (+-M) /0/T.O1A parameter values.

    1un the 2O1A3456OM5&avavm&install&initvm.s7l script !rom S8S AS S8S9#A to install the

    Oracle JServer Option on a database.

    :rant JAVA;S514 statements or 4 code. 4oo$ at this eample

    create or relace %unction ,ello (tr varc,ar0) return varc,ara language java name ello.g(java.lang.String) returnjava.lang.String# K

    #ac$ to top o! !ile

    What is JDBC and what is it used for?

    J9#3 is a set o! classes and inter!aces written in Java to allow other Java pro"rams to send S>4 statementsto a relational database mana"ement system.

    Oracle provides three cate"ories o! J9#3 drivers

    http://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.orafaq.com/scripts/plsql/java.txthttp://www.orafaq.com/scripts/plsql/java.txthttp://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.orafaq.com/scripts/plsql/java.txthttp://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.orafaq.com/faqjdbc.htm#TopOfFile
  • 8/11/2019 jdbc_doc03

    11/17

    J9#3 Thin 9river (0o local 0et? installation re7uired& handy !or applets)

    J9#3 O3/ !or writin" stand@alone Java applications

    J9#3 5SIOG')# w,ile (ret.net())

    http://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.orafaq.com/faqjdbc.htm#TopOfFile
  • 8/11/2019 jdbc_doc03

    12/17

    Sytem.out.rintln (ret.getString(1))# KK *rint col 1 tmt.cloe()# 88

    #ac$ to top o! !ile

    How does one connect with the JDBC OC Driver?

    One must have 0et? (S>4B0et) installed and wor$in" be!ore attemptin" to use one o! the O3/ drivers.imort [email protected]#cla +bcetion 7 try 7 Cla.%orGame ('oracle.j+bc.+river.Oracle;river')# 8 catc, (ClaGot$oun+>cetion e) 7 e.rintStac:9race()# 8

    Connection conn = ;riveranager.getConnection ('j+bc/oracle/ociU/Q@itu@cbiworcl' 'cott' 'tiger')# KK or ociV Q9GSGame>ntry ueri+ awor+

    Statement tmt = conn.createStatement()# 5eultSet ret = tmt.eecute6uery('elect B5 %romSRS.JTJ>5SIOG')# w,ile (ret.net()) Sytem.out.rintln (ret.getString(1))# KK *rint col 1 tmt.cloe()# 88

    #ac$ to top o! !ile

    How does one connect with the JDBC !"#B Driver?

    One can obtain a handle to the de!ault or current connection (

  • 8/11/2019 jdbc_doc03

    13/17

    8

    #ac$ to top o! !ile

    Where can one $et %ore info about JDBC?

    9ownload Sun's Java 9evelopers it and various other A4 access in Java. /t provides a Java precompiler that translatesS>4J call to J9#3 calls. The idea is similar to that o! other Oracle 4J is more concise and thus easier to write than J9#3E and provides compile@time schema validationand synta chec$in" !or easier debu""in". S>4J reads input either !rom a B.S>4J !ileE or a Java source !ilein which S>4J statements are embedded. The S>4J precompiler translates the S>4J statements into theire7uivalent J9#3 calls. S>4J supports static S>4.

    #ac$ to top o! !ile

    How does one write S&J pro$ra%s?

    See the Scripts and sample pro"ramssection !or some S>4J eample pro"rams. #ac$ to top o! !ile

    How does one deploy S&J pro$ra%s?

    ;se the s7l compiler to compile your B.s7l !iles to B.ava and B.ser !iles. The B.ser !iles contain vendorspeci!ic database code. Therea!ter one invo$es the avac compiler to compile the .ava !iles to B.class !iles.The B.class and B.ser !iles needs to be deployed. #ac$ to top o! !ile

    Where can one $et %ore info about S&J?

    The S>4J Or"ani*ation

    Sun's /n!o#us 3ontrols

    #ac$ to top o! !ile

    What is JDeveloper and what is it used for?

    http://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://java.sun.com/products/jdbc/http://java.sun.com/docs/books/tutorial/jdbc/basics/gettingstarted.htmlhttp://java.sun.com/docs/books/tutorial/jdbc/basics/gettingstarted.htmlhttp://www.oracle.com/downloadhttp://sunsite.unc.edu/javafaq/javafaq.htmlhttp://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.orafaq.com/faqpro.htmhttp://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.orafaq.com/faqscrpt.htm#SQLJhttp://www.orafaq.com/faqscrpt.htm#SQLJhttp://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.sqlj.org/http://www.sqlj.org/http://java.sun.com/beans/infobus/http://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://java.sun.com/products/jdbc/http://java.sun.com/docs/books/tutorial/jdbc/basics/gettingstarted.htmlhttp://www.oracle.com/downloadhttp://sunsite.unc.edu/javafaq/javafaq.htmlhttp://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.orafaq.com/faqpro.htmhttp://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.orafaq.com/faqscrpt.htm#SQLJhttp://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.orafaq.com/faqjdbc.htm#TopOfFilehttp://www.sqlj.org/http://java.sun.com/beans/infobus/http://www.orafaq.com/faqjdbc.htm#TopOfFile
  • 8/11/2019 jdbc_doc03

    14/17

    J9eveloper is the Oracle /95 (/nte"rated 9evelopment 5nvironment) !or developin" S>4J and J9#3pro"ramsE appletsE stored proceduresE 5J#'sE JS

  • 8/11/2019 jdbc_doc03

    15/17

    How does a JS" $ets e*ecuted?

    The !irst time you call a JS

  • 8/11/2019 jdbc_doc03

    16/17

    How does on drop a Java Stored "rocedure fro% the database?

    S>4B4B4J s7l K call ...L e" s7l K call A3M5.#5:/0150TA4(in member/9E in

    employee/9E outE ...) LH

    import ava.s7l.BH

    public class 3reate3o!!ees K public static void main(Strin" ar"sN) K Strin" url =dbcmySubprotocolmy9ataSource=H 3onnection conH Strin" createStrin"H createStrin" =create table 3O%%55S = P =(3O%0AM5 VA136A1(Q,)E = P

    =S;

  • 8/11/2019 jdbc_doc03

    17/17

    L catch(S>45ception e) K System.err.println(=S>45ception = P e."etMessa"e())H L L

    L