How to implement getConnection () in a DataSource in Java?

I am reading on a DataSource, here and trying to implement it in my own small project, using a simple file as my "data source". I created a class that is pretty simple at the moment ...

public class QueueData implements DataSource { ... }

although the reason is simple because I could not find a resource explaining how the implemented methods should work. It seems everyone just lists the context initialization and the magic call to getConnection (), for example.

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

But can any of you give me an example of what the code inside getConnection () should look like?

+3
source share
3 answers

, , DataSource, "" , , JDBC ( ).

, , , Connection, , . -, SQL .

:

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

, , .

DataSource , , :

+3

Connection , , . getConnection() . ... (, , .)

DataSource? in-process ( , ), HSQLDB ( ), H2 (Wiki)...

#, Linq To XML, , Java- ...

+2

. DataSource, JNDI, , . , , URL- , , DataSource ( jdbc, ). DataSource, , .

Let's say that you want to write your own implementation that gives the client a NOOP connection (a connection object on which all operations give nothing). All you have to do is "register" the user implementation DataSourcewith the server JNDI application servers. This implementation method getConnection()simply returns a class that implements the Connection interface and methods that do nothing.

+2
source

Source: https://habr.com/ru/post/1772605/


All Articles