How to implement getconnection () in datasource in Java?

I'm reading datasource, here and trying to implement it in my own small project by using a simple file as my "data source" I created a very simple course

public class QueueData implements DataSource { ... }

Although it's simple, the reason is that I can't find resources to explain how the implementation method should work Everyone seems to list only one context initialization and a magical getconnection () call, like this

Context ctx = new InitialContext(env1);
    DataSource ds = (DataSource)ctx.lookup("jdbc/mydatasource");
    Connection conn = ds.getConnection(); // Magical method!

But can one of you really give me an example of what the code in getconnection () should look like?

Solution

The reason why no one shows how the samples implement datasource and "just" use them is because only jdbc driver vendors (usually database manufacturers) need to write them

What it should do, of course, is to return a connection object. It also needs to be an instance of a driver specific class In your case, you can accept what SQL statements read from the file

Your code might look like this:

public Connection getConnection(){
      final String fileName = getFileNameFromMyDatabaseUrl();
      return new MyFileConnection(new File(fileName));
 }

Of course, this is not very interesting code

You can look at some open source datasource implementations to see what they do:

>Apache commons DBCP poolingdatasource > Apache Derby's embeddeddatasource (embedded database written in Java) > PostgreSQL's basedatasource (abstract base class of PostgreSQL jdbc driver)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>