SQL Embedded in Java - Part 2 @ JDJ

779 篇文章 0 订阅
<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>

  It began sometime in late '96 or early '97 - JDK 1.0 still ruled and Tandem was still called Tandem, not Digital or Compaq - when people from IBM, Tandem and Oracle met and started to muse.

  "Wouldn't it be nice to have SQL Embedded in Java just as it's Embedded in other host languages? However, we don't just want to copy previous efforts but to do justice to the Java language." Of course, the embedding would have to permit the use of compiled SQL statements and be just as portable as Java code. It would also need to provide the easiest, most robust way to write SQL code in Java. Sun, Sybase and informix soon joined the fray....and the "JSQL" effort was born.

  "Gotcha," you're thinking. "You meant to say SQLJ, didn't you?" Well, yes and no - hold off just a second. The JSQL enterprise was all about Java programs that call SQL. When the same informal intercompany working group also embarked on an effort to describe the implementation of SQL stored procedures and functions in Java (christened SQLJ, since it kind of goes in the opposite direction - SQL procedures that "call" Java in their body), this became known as SQLJ Part 1. And when they started yet another project to describe how an SQL database could store Java objects in table columns and also publish them as SQL types, this was called SQLJ Part 2. When the time came to submit JSQL to the ANSI standards committee, it turned out that the name was already a registered trademark of Caribou Lake Software for their JDBC drivers. So what did that bewildered bunch of computer scientists do when they realized they'd goofed? The same thing they've done since the dawn of the computer age: they started counting from zero! Thus SQLJ Part 0 was born.

  On the other hand, the ANSI people don't refer to it as Part 0; in fact, they don't even refer to it as SQLJ: to them it's SQL Part 10: Object Language Bindings. ANSI put its imprimatur on SQLJ Part 0 around the end of 1998. Since then, SQLJ has been winding its merry way through the international Standards Organization, picking up a bunch of JDBC 2.0 features along the ride.

  But enough history; let's get back to serious business. in this article I'm going to cover the following ground:

  A reprise of SQLJ iterators: all about positional iterators

  Calling stored procedures and functions in the database

  Reflections on bridging the gap between SQL types and Java types

  As with Part 1 of this series of articles, I'll be giving various tips and exercises on the way through.

  Get into Position!

  SQLJ provides two flavors of iterators. Last month we looked at named iterators, in which you specify both the Java column types and the column name. Remember that the name also appears as the accessor function with which you retrieve the column value. This kind of iterator is most "Java-ish," and JDBC programmers immediately feel familiar with it.

  Today I'll be taking a closer look at positional iterators. They're characterized by the order and by the Java types of their columns. Positional iterators require neither the next() method nor the accessors of the named iterator. They use a FETCH statement to advance to the next row and retrieve the column values into a list of variables all at once. Each variable in the inTO clause corresponds to exactly one column in the SELECT list in the same order. This will look familiar if you're used to other languages with Embedded SQL.

  #SQL { FETCH :p inTO :name, :salary };

  Declarations for positional iterator types are even simpler than for the named variety.

  #SQL iterator PosIter (String, Double);

  in the processing loop for a positional iterator, you issue FETCH statements to retrieve the next row of data into host variables. After a FETCH, the endFetch() call returns true if the FETCH was successful and false if there was no row left that could be fetched. Also remember to call close() on any iterator - named or positioned - once you're done using it or you'll find yourself running out of database resources. The following example uses a positional iterator:

  String name = null;

  Double salary = null;

  PosIter p;

  #SQL p = { SELECT ename, sal FROM emp };

  while (true) {

  #SQL { FETCH :p inTO :name, :salary };

  if (p.endFetch()) break;

  System.out.println(name + " would like to make " + (salary * 2));

  }

  p.close();

  Tip: Even though it might look somewhat unusual, you should always employ the following template when using positional iterators:

  Let's Get Results - Functions First

  We've already seen how results can be received from an SQL statement when we used the SELECT-inTO statement. More often, results from an SQL operation are returned through an SQLJ assignment statement. Let's look at a call to an SQL function SYSDATE():

  Java.SQL.Date today;

  #SQL today = { VALUES( SYSDATE() ) };

  System.out.println("The database thinks that today is "+today);

  The VALUES( ... ) syntax is SQLJ-specific syntax for calling a stored function. Such functions might also take arguments, as in the following code snippet in which Next_Paycheck is an SQL stored function that returns the date of the next paycheck on or after a given date:

  String moreMoney;

  #SQL moreMoney = { VALUES( Next_Paycheck(:today) ) };

  (Note that we can receive an SQL DATE value in different formats in Java - in our examples, as a Java.SQL.Date and as a Java.lang.String.)

  Are We Outmoded Yet? - Getting into Procedures

  in the foregoing discussion we glossed over the fact that host variables or expressions are used in different modes:

  in: The value of the expression is sent to the database.

  OUT: The expression denotes a location and receives a value from the database.

  inOUT: All of the above.

  Host expressions, by default, have the mode in - with the exception of host expressions in inTO-lists and the return value of a stored function call, which have the mode OUT. in all other cases you have to explicitly prefix the host expression with the mode. SQL stored procedures can have parameters with all three modes. The SQLJ syntax for calling a stored procedure is illustrated in the following code fragment:

  int x = 10;

  int y;

  int z = 20;

  #SQL { CALL Toutes_Les_Modes( :x, :OUT y, :inOUT z ) };

  Tip: You must add OUT or inOUT modes to all host expressions in procedure arguments that don't have the mode in. Otherwise you won't see any values returned from the database in these positions. A good way to ensure that you've specified all the required modes is to run the SQLJ translator with online checking.

  What Type Are You?

  So far, we've used a bunch of Java types in our SQLJ programs without having a clue which types are permitted and how they're used. SQLJ includes all of the JDBC types with some additional twists. Following is a list of JDBC-supported Java types and how they're used in SQLJ. Please see the sidebar ("Coming Soon: Scrollable Iterators") for JDBC 2.0-specific type support.

  Numeric types: This includes: int, integer, long, Long, short, Short, byte, Byte, boolean, Boolean, double, Double, float, Float and - just to prove I don't stutter - Java.math.BigDecimal. So what's the deal with supporting both the primitive type (such as int, or double) and the corresponding Java object type (such as integer, or Double)? in SQLJ the SQL NULL value always maps to Java null - and vice versa. Thus, if you retrieve an SQL NULL value into an integer, you receive a Java null, but if you try to read it into an int, you'll only get an SQLj.runtime.SQLNullException, which is a subclass of SQLException.

  Character types: The Java type String represents these very well, thank you. Note that the Java char and Character types aren't supported by SQLJ or by JDBC (besides, they could only hold a single character, anyway). Also useful are the character streams SQLj.runtime.AsciiStream and SQLj.runtime.UnicodeStream. One peculiarity about SQL is that columns defined as SQL CHAR type are automatically blank-padded. If you don't get the same string back that you inserted into the database, or if SQL comparisons with a given Java string fail mysteriously, you should check the SQL type used in your table.

  Date and time types: These include Java.SQL.Time, Java.SQL.Timestamp and Java.SQL.Date. Yes, that's Java.SQL.Date and not Java.util.Date - don't confuse the two!

  Raw types: Raw data can be represented as byte[], aka "byte-array," or - in stream form - as SQLj.runtime.BinaryStream, discussed next.

  Stream types: SQLJ provides new stream types SQLj.runtime.BinaryStream, SQLj.runtime.AsciiStream and SQLj.runtime.UnicodeStream for wrapping a LONG (or LONG RAW) column in the database. These three stream types implement a Java.io.inputStream. When you retrieve a LONG column, data in the same row prior to that column may be lost by some JDBC drivers (such as Oracle's). This imposes limitations on positional iterators (at most, one stream column is permitted, and it must also be the last column of the iterator) and it requires extra care when using named iterators (columns must be accessed in SELECT sequence). You could use byte arrays or Strings to circumvent these problems.

  Tip: SQLJ (and SQL) perform quite a few implicit conversions between SQL and Java types. Although this can be useful, it may also lead to surprising and unexpected behavior. It is strongly recommended that you run the SQLJ translator online to check your program. However, the type checking this provides isn't adequate to guarantee the correct use of SQL types.

  Exercise: investigate conversions between Java types and SQL types:

  Take a positional iterator that contains a String column and an int column. What happens if you flip the corresponding host variables in the FETCH statement?

  What happens if you flip the corresponding columns in the SELECT statement?

  Get It Your Way - With Customization

  Vendors need to be able to customize the way SQLJ programs are executed for their database. Take the following PSM set statement, for example.

  SET :x = 2 + 2

  Against an Oracle database, however, this would have to be written as follows.

  BEGin :OUT x := 2 + 2; END;

  The Oracle customizer (see Figure 1) takes an existing serialized profile and adds Oracle-specific information to it - in this case the new SQL text. At runtime the actual database connection is used to determine which vendor's customization/runtime pair becomes activated. If no customization exists for a given connection, SQLJ reverts to using the standard JDBC API.

  Okay, let's call it a day. Next time we'll cover (almost) everything else there is to know about SQLJ. I'll teach you some neat translator tricks for the command line. You'll also be initiated into the mysteries of execution contexts and connection contexts. Finally, we'll examine how JDBC and SQLJ can live in blissful harmony happily ever after. in the meantime, keep your feedback, your answers to exercises and your questions coming!

<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
<script type="text/javascript"> </script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值