Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Get database connection from java code

 
Saurabh Agarwal
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I have followed below two approaches. Both are successfull. I want to understand difference in between both below approaches.

Approach 1 :
InitialContext ctx = new InitialContext();
DataSource dataSource =
(DataSource) ctx.lookup(readPropertyFiles()); // Reading properties file from Local c drive. Content of this file are : "jdbc/<Database User Id>"

conn = dataSource.getConnection();
=======================================================================================

Approach 2:

String driver = "oracle.jdbc.driver.OracleDriver";
String username = "xxxxdb";

String password = getDatabasePwd();
Class.forName(driver);
this.con2 = DriverManager.getConnection(this.dbName, username, password);
 
Alice Hampton
Ranch Hand
Posts: 217
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is one not more dynamic than the other?Given that the second has everything set up to a specific driver so it won't deviate from that. I 've only ever used the second version myself, I've never come across anything like your first version. I'd be interested in learning if perhaps one of them is more reliable or just better than the other and the reasoning behind it. I hope you manage to get an answer a little bit more in depth than mine however
 
Ulf Dittmer
Rancher
Posts: 42969
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Approach 1 (a.k.a. JNDI) is used when the DataSource is defined outside of the code, for example in web apps or JEE apps where it'd be defined as part of the server setup. That way the DB setup is completely separated from the application itself. That's often useful in situations where sys admins and developers work separately - that way developers don't have to worry about the details of the external systems their code accesses (they only need to know the JNDI name like "jdbc/myDB"), and sys admins are free to change those without having to touch the code. JNDI is also used to set up mail servers, JMS queues and other external dependencies.

Otherwise, both approaches are similar in that they result in the code having obtained a DB connection.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic