0

I am trying to make a java application using netbeans. I want to enter the JDBC connection details(class name, hostname, username and password) at runtime, so that the application is more effective. Is there any way to do that?

If not in netbeans, then can it be done in eclipse?

By dynamically entering, the hostname, I mean the JDBC class name, hostname&port and username, password. My main aim is to enter these values from the frontend(java application itself). Can it be done? or I heard configuration files, if its not possible from front end, can anyone please tell how to use these create and use these configuration files?

Sunny
  • 1
  • 5

1 Answers1

0

Of course it's possible, and it doesn't have to do with your IDE. The trick is to make sure dependencies are always passed to objects that need them. It's called inversion of control.

Here's an example that takes a DataSource as a dependency.

public class DbAccessClass {
    private final DataSource dataSource;

    public DbAccessClass(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public doSomething() {
        dataSource.getConnection();
        // use connection
    }
}

Then all you have to do is present the user with a dialog to input those four strings and construct your DataSource and pass it to construct your DbAccessClass. Here's an example using BasicDataSource.

String driver = // get driver field value from UI
String url = // get url field from UI
String user = // get user field
String pass = // get pass field
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(user);
ds.setPassword(pass);
new DbAccessClass(ds);

I would only go with this approach if your user actually knows the connection details. Often it's more valuable to keep them tucked away in a config file.

Community
  • 1
  • 1
Samuel
  • 15,583
  • 5
  • 54
  • 70
  • Thanks Samuel..I will try this approach and let you know. Meanwhile, can you tell me how to create config files and how to use them? – Sunny Sep 11 '15 at 18:25
  • Nevermind, I was a newbie then, now I am able to do. Thanks Samuel. – Sunny Aug 01 '18 at 20:25