0

Is it possible to connect to a datasource defined in another class, without any frameworks or servers etc just for a local application, built just for practice.

I have a class called FireBirdDataSource:

import org.firebirdsql.pool.FBWrappingDataSource;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class FireBirdDataSource {
public FireBirdDataSource() {
    InitialContext context = null;
    FBWrappingDataSource dataSourceFB = new FBWrappingDataSource();
    dataSourceFB.setDatabase("jdbc:firebirdsql:localhost/3050:C:\\DB.fdb");
    dataSourceFB.setUserName("SYSDBA");
    dataSourceFB.setPassword("masterkey");
    try {
        context = new InitialContext();
        context.bind("jdbc/FBDB", dataSourceFB);
    } catch (NamingException e) {
        e.printStackTrace();
    }

}
}

Trying to connect to it with:

   InitialContext context = new InitialContext();
        DataSource dataSource = (DataSource)context.lookup("jdbc/FBDB");
        Connection con = dataSource.getConnection();

The Connection con = dataSource.getConnection() - can't find the getConnection() method. I seem to be doing something really wrong, but I'm not quite sure what.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Novice
  • 145
  • 2
  • 2
  • 9
  • Are you sure you are casting to `java.sql.DataSource` and not to - for example - `javax.activation.DataSource`? – Mark Rotteveel Apr 02 '16 at 10:17
  • Also, did you ever call the constructor of `FireBirdDataSource`, otherwise nothing is bound. Note though that registering a data source this way is a bit atypical. – Mark Rotteveel Apr 02 '16 at 10:46
  • Yep, calling the constructor of FireBirdDataSource. Yep, was casting an incorrect DataSource. Now I get "javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial " I've looked about the DataSource and seems it's mostly defined in some property file usually, am I right? – Novice Apr 02 '16 at 14:58
  • 1
    What sort of application is this? If it runs in an application server or something like tomcat, then you should create the datasource through configuration, not in code. If it is a standalone application, then consider just using a class to hold and initialize a static data source instead of going through the hoops required to get JNDI running. – Mark Rotteveel Apr 02 '16 at 15:41
  • Thanks, Mark :) I dropped the JNDI thing for now. – Novice Apr 03 '16 at 15:53

0 Answers0