Java Reference
In-Depth Information
}
}
}
}
catch (SQLException sqlex)
{
while (sqlex != null)
{
System.err.println("sql
error
:
"+sqlex.getMessage());
System.err.println("sql
state
:
"+sqlex.getSQLState());
System.err.println("error
code:
"+sqlex.getErrorCode());
System.err.println("cause: "+sqlex.getCause());
sqlex = sqlex.getNextException();
}
}
}
Thismethodmostimportantlydemonstrateshowtoserializean
ImageIcon
object
to a
java.sql.Blob
object, and then store the
Blob
object in a table column of
BLOB
type.
Youfirstinvoke
Connection
's
Blob createBlob()
methodtocreateanobject
that implements the
Blob
interface. Because the returned object initially contains no
data,youneedtocall
Blob
's
OutputStream setBinaryStream(long pos)
method(
pos
ispassedthe1-basedstartingpositionwithintheblobwherewritingbe-
gins) or one of its overloaded
setBytes()
methods.
Ifyouchoose
setBinaryStream()
,youwouldthenuseobjectserialization(see
streamwhenyou'refinished—thetry-with-resourcesstatementnicelyhandlesthistask
for you.
After the
Blob
object has been created and populated, call one of
Pre-
paredStatement
's
setBlob()
methods (e.g.,
void setBlob(int para-
meterIndex, Blob x)
)topasstheblobtothepreparedstatementbeforeitsexe-
cution. Following this execution, the blob must be freed and its resources released.
Consider the following
loadDB()
source code: