Java Reference
In-Depth Information
Read From and Write To the Database
As far as the database knows, we're dealing with only two fields,
player_name
and
location_strings
, which use the
player_name
as a key.
Looking back at
LocationSnapshot
, you can copy the database's
load
and
update
functions, with the exception handling, and make two new functions here:
private void
myRead(
final String
name) {
}
private void
myWrite() {
}
In each function, set up the search
HashMap
, then do the Database's
load
or
update
in a
try-catch
block.
Go try that now. When you're done, you should have something like this:
private void
myRead(
final String
name) {
player_name = name;
HashMap
<
String
,
Object
> search =
new HashMap
<
String
,
Object
>();
search.put(
"player_name"
, name);
try
{
Database.get().load(this, search);
}
catch
(DatabaseReadException e) {
// Not necessarily an error, could be first one
}
if
(location_strings == null) {
player_name = name;
location_strings =
new ArrayList
<
String
>();
}
}
private void
myWrite() {
HashMap
<
String
,
Object
> search =
new HashMap
<
String
,
Object
>();
search.put(
"player_name"
, player_name);
try
{
Database.get().update(this, search);
}
catch
(DatabaseWriteException e) {
//Error, couldn't write!
System
.err.println(
"Update failed"
);
}
}
Make sure that much compiles, using
build.sh
as usual.