Java JDBC using SQLite/Extending the base class
Extending the Base Class
[edit | edit source]Let's now turn to extending and implementing our concrete class. First we'll create a concrete implementation of the base abstract class with no additional functionality:
public class MyDb extends Db
{}
We can now call our database connector in our codebase and invoke it with the driver name and the url using the parameterised constructor.....
String sUrlString = "jdbc:sqlite:hello.db";
MyDb mydb = new MyDb("org.sqlite.JDBC",sUrlString);
Here we have these parameters hard-coded but typically you would have these values stored as values against keys in a properties file and load them from there.
Now let's move on and add some functionality to the MyDb child.
public class MyDb extends Db
{
public MyDb(String sDriverKey, String sUrlKey)
{
init(sDriverKey, sUrlKey);
if(conn != null)
{
System.out.println("Connected OK using " + sDriverKey + " to " + sUrlKey);
}
else
{
System.out.println("Connection failed");
}
}
}
Interesting but not particularly useful. However the parameterised overload should be saying to you that if you can do this in a generic sort of way, there is nothing to stop you from making a per database type subclass; e.g. from Db you could subclass not only SqliteDb, but also OracleDb, MySqlDb etc, etc, and add to these the required database specific functionality.
public class SqliteDb extends Db
{
String sDriverForClass = "org.sqlite.JDBC";
public SqliteDb(String sUrlKey)
{
init(sDriverForClass, sUrlKey);
[..] etcetera
The implications of this should be becoming apparent. By carefully structuring your class hierarchies and relationships, it is possible to provide as much or as little appropriate functionality as is necessary.
- Next page: Working with data
- Previous page: Example base class