I have a project that needs to connect to a database. I'm reading the database connection info in from a config.xml file, however, I'm stuck on the part where I define the DataSource for a particular db engine (technically, it's the dbms, but the terms seem to be used interchangeably). Here's the relevant code snippet:
String engine = get(xmldoc, "engine");
if (engine == "postgres")
{
PGSimpleDataSource ds = new PGSimpleDataSource();
}
else if (engine == "mssql")
{
SQLServerDataSource ds = new SQLServerDataSource();
}
else if (engine == "sqlite")
{
SQLiteDataSource ds = new SQLiteDataSource();
}
else
{
throw new Exception(String.format("Unknown DBMS type %s", engine));
}
ds.setServerName(get(xmldoc, "hostname"));
ds.setDatabaseName(get(xmldoc, "databasename"));
ds.setUser(get(xmldoc, "username"));
When I try to compile it, I get a bunch of error: cannot find symbol
for every reference to ds
. After a little digging, I found that this is because my ds variable is local to the if-statement in which it's declared (ref: Cannot find symbol if statement error). Unlike in that question though, I can't simply declare it at the beginning because I don't know what particular DataSource it's going to be.
So, what is the best approach to dynamically set my DataSource? Preferably without putting all my initialization code inside each if-statement because then I'd have to put all my db calls there as well. Is there some way to initially declare ds
to be a generic DataSource and then cast it to a particular one in the if-statements?