如何在Java中的DataSource中实现getConnection()? [英] How do I implement getConnection() in DataSource in Java?

查看:1248
本文介绍了如何在Java中的DataSource中实现getConnection()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读DataSource,这里,并试图通过使用一个简单的文件作为我的数据源在我自己的小项目中实现它。我创建了一个类,现在很简单...

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

public class QueueData implements DataSource { ... }

虽然简单的原因是因为我找不到资源,实现的方法应该工作。每个人似乎只是列出一个上下文的初始化和一个神奇的getConnection()调用,像这样。

though the reason it is simple is because I haven't been able to find a resource that explains how the implemented methods should work. Everyone seems to just list the initialization of a context and a magical getConnection() call, like so.

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



< ?

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

推荐答案

没有人显示样本如何实现DataSource,而just使用它们的原因是因为只有JDBC驱动程序供应商(通常是数据库制造者)需要写它们。

The reason no one shows samples how to implement a DataSource and "just" uses them instead is because only JDBC driver vendors (usually database makers) need to write them.

它应该做的是当然返回一个Connection对象,它还需要一个驱动程序的实例类。

What it should do is of course return a Connection object that will also need to be an instance of of a driver-specific class. In your case, something that can accept SQL statements to read from a file.

您的代码可能如下所示:

Your code could look something like this:

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

这当然不是很有趣的代码。

Which of course is not very interesting code, either.

您可以查看一些开源的DataSource实现,看看他们做了什么:

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

  • Apache Commons DBCP PoolingDataSource (a connection pool)
  • Apache Derby's EmbeddedDataSource (an embedded database written in Java)
  • Postgresql's BaseDataSource (abstract base class for the Postgresql JDBC driver)

这篇关于如何在Java中的DataSource中实现getConnection()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆