XKCD #327 (http://xkcd.com/327/)
Use a PreparedStatement
!
May I suggest:
try (final PreparedStatement preparedStatement = con.prepareStatement(sql)) {
if (album instanceof CDAlbum) {
CDAlbum cdAlbum = (CDAlbum) album;
preparedStatement.setString(1, "CD");
preparedStatement.setString(2, cdAlbum.getTitle());
preparedStatement.setString(3, cdAlbum.getGenre());
preparedStatement.setString(4, cdAlbum.getArtist());
preparedStatement.setString(5, cdAlbum.getTracks());
} else if (album instanceof DVDAlbum) {
DVDAlbum dvdAlbum = (DVDAlbum) album;
preparedStatement.setString(1, "DVD");
preparedStatement.setString(2, dvdAlbum.getTitle());
preparedStatement.setString(3, dvdAlbum.getGenre());
preparedStatement.setString(4, dvdAlbum.getDirector());
preparedStatement.setString(5, dvdAlbum.getPlotOutline());
}
dvdAlbum.getPlotOutline();
}
This prevents any possibility of weird values in the data causing the query to fail. Also note that I use a try-with-resources
construct, this will always close the resources. Your current code has a memory leak if there is an error in the query - the exception will be thrown and the close()
calls with be skipped. You have this issue in many places, when you read the file, when you open the connection, etc...
I have also changed your if...if
to an if...else if
as I suppose it's unlikely that a CDAlbum
would also be a DVDAlbum
. A naming note - acronyms in class names are best expressed as words - DvdAlbum
rather than DVDAlbum
.
Further I would suggest that you learn about method overloading as well as polymorphism. Any use if instanceof
in your code is a sure sign of code smell.
Although the whole idea of storing completely disparate data in the same table is a sure sign of design problems. Further, fields like tracks
- surely that needs to be another table?!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…