【问题标题】:connecting to derby database with tomcat as the server以tomcat为服务器连接derby数据库
【发布时间】:2012-07-10 20:28:44
【问题描述】:

我如何连接到 derby 数据库(netbeans 自带的)?我使用 Tomcat 作为服务器。之前我使用以下语句连接到 derby 数据库,但后来我使用glassfish 作为服务器。

Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/PollDatasource");
Connection connection = ds.getConnection();

但现在使用 Tomcat 作为服务器我不知道如何做到这一点。

注意:Tomcat 和 Derby 预装了我当前使用的 netbeans IDE

【问题讨论】:

  • 配置 JNDI数据源了吗?
  • @AVD 没有配置过
  • 请参阅此url 和@Raknel 帖子。

标签: java jakarta-ee tomcat database-connection derby


【解决方案1】:

在Tomcat中找到conf/context.xml,然后编辑并编写如下内容:

<Resource name="jdbc/PollDatasource" auth="Container" type="javax.sql.DataSource"
    driverClassName="com.YourDriver" 
    url="jdbc:derby://localhost:1527/nameOfTheDatabase;create=true"
    username="username" password="password" maxActive="20" 
    maxIdle="10" maxWait="-1" />

注意 1:使用上述 URL,驱动程序将是 org.apache.derby.jdbc.ClientDriver

注意 2:您也可以在项目的 META-INF/context.xml 中添加上述信息。这成为特定于应用程序的。如果您在 tomcat 的 context.xml 中添加信息,就会变成全局。

注意3:从this website下载jar。下载db-derby-10.9.1.0-bin.zip。它包含很多文件,包括derby.jar和derbyclient.jar(还有很多文档).derbyclient.jar 包含我们的朋友org.apache.derby.jdbc.ClientDriver.class。 derby.jar 包含org.apache.derby.jdbc.EmbeddedDriver。将下载的jar保存在Tomcat的lib文件夹中。

在你的应用程序 web.xml "resource-ref" 中:

<resource-ref>
    <description>my connection</description>
    <res-ref-name>jdbc/PollDatasource</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>

你可能想看看这些问题:

【讨论】:

  • 这是 JDBC 驱动程序的名称,特定于数据库。对于您的应用程序,它将是 org.apache.derby.jdbc.EmbeddedDriver。你可以在 jar 中下载这个:mvnrepository.com/artifact/org.apache.derby/derby
  • 我添加了这些标签但得到了exception
  • 您能否解释一下在尝试连接时如何查找这些标签。我在应用这个和理解这个方面有问题
【解决方案2】:

你需要:

1) 将您的derbyclient-*.jar 复制到${TOMCAT_HOME}/lib

2) 编辑您的 server.xml 并将以下行添加到 GlobalNamingResources 部分:

 <Resource auth="Container" 
           driverClassName="org.apache.derby.jdbc.EmbeddedDriver" 
           maxActive="8" maxIdle="4" 
           name="jdbc/my-ds" type="javax.sql.DataSource" 
           url="jdbc:derby:mydb;create=true" 
           username="myuser" password="mypassword" />

3) 在您的上下文定义中,添加:

 <Context docBase="myapp"
          path="/myapp"
          reloadable="true"
          ...>
    <ResourceLink name="jdbc/my-ds"
                  global="jdbc/my-ds"
                  type="javax.sql.DataSource" />
 </Context>

4) 重启 Tomcat。

【讨论】:

  • I added these tags but get an exception.虽然我已经在我的项目中编辑了tomcat的context.xmlweb.xml
  • 赞成这个,因为我偶然发现了它,它非常适合我当前的应用程序。
【解决方案3】:

您的示例需要 JNDI。有关设置,请参阅相关的 tomcat 版本文档。

或者使用连接字符串,这里是德比文档http://db.apache.org/derby/integrate/plugin_help/derby_app.html的页面

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 2011-09-24
    • 2016-07-12
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    相关资源
    最近更新 更多