Statement rows are represented in rdbc as
Row trait. This chapter describes
this trait and methods it provides that give access column values.
Row trait declares a family of
col methods that allow accessing column
values of any Scala type. The methods accept a single type parameter telling
rdbc what Scala type should be used to represent a database value — see
the list below for their simplified declarations.
def col[A](idx: Int): A
def colOpt[A](idx: Int): Option[A]
def col[A](name: String): A
def colOpt[A](name: String): Option[A]
The methods differ from one another in two areas:
Named vs unnamed columns
To fetch column value by name use method that accepts a
String; to fetch value by column's index, use the version that accepts an
Int. Index is 0 based.
colOptmethods are null-safe, and
colmethods aren't. You can't use plain
colmethod to get SQL
NULLvalues. If you try that,
ConversionExceptionwill be thrown.
Optionso it's fit for handling
NULLs — it represents them by
colmethod is intended to be used only for columns that can't hold
NULLvalues, for example because there is a not-null constraint defined for them.
Examples below show how to use
col methods on rows produced by
select first_name, last_name, age from persons
/* fetches first_name. If value is NULL ConversionException will be thrown */ row.col[String](0) /* fetches last_name. If value is NULL ConversionException will be thrown */ row.col[String]("last_name") /* fetches age. If value is NULL, None will be returned */ row.colOpt[Int](2)
Row trait, for convenience, also provides methods that aren't parametrized
by type and their names reflect the type they return. They are simply shortcuts
for calling generic
col methods described earlier. For instance, there is a
str method that is a shortcut for calling
col[String] method. See the
Row Scaladoc for a complete list.
Previous example could be rewritten as follows:
/* fetches first_name. If value is NULL ConversionException will be thrown */ row.str(0) /* fetches last_name. If value is NULL ConversionException will be thrown */ row.str("last_name") /* fetches age. If value is NULL, None will be returned */ row.intOpt(2)
If you want to use types supported by the particular driver but not supported
by default by rdbc, you must always use generic