Tomcat6 MySql JDBC数据源配置 [英] Tomcat6 MySql JDBC Datasource configuration
问题描述
我一直使用Spring的依赖注入来获取数据源对象,并在我的DAO中使用它们,但是现在,我必须编写一个没有该依赖的应用程序.
I've always used Spring's dependency injection to get datasource objects and use them in my DAOs, but now, I have to write an app without that.
在Spring中,我可以这样写:
With Spring I can write something like this:
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1/app?characterEncoding=UTF-8" />
<property name="username" value="u" />
<property name="password" value="p" />
</bean>
但是在没有Spring或其他任何东西的情况下,如何在DAO中使用数据源呢?我仅使用servlet和JSP.性能是非常重要的因素.
But how can I use datasource in my DAOs without Spring or anything? I'm using servlets and JSPs only. Performance is very important factor.
推荐答案
信不信由你,人们在Spring之前编写应用程序,但有些人仍未使用它:)在您的情况下,您可以使用Tomcat连接池(在那里是文档).让我总结一下:
Believe it or not, people were writing applications before Spring and some are still not using it :) In your case, you could use Tomcat connection pool (and there is a complete configuration example for MySQL in the documentation). Let me summarize it:
首先,将驱动程序放入$CATALINA_HOME/lib
.
First, put your driver in $CATALINA_HOME/lib
.
然后,通过在
在您的 并在您的应用程序中通过JNDI查找获得数据源: And get the datasource with a JNDI lookup in your application: 请注意,此类 Note that such 这篇关于Tomcat6 MySql JDBC数据源配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!web.xml
中声明此资源:<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<description>MySQL Test App</description>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");
Connection conn = ds.getConnection();
... use this connection to access the database ...
conn.close();
lookup
通常用 ServiceLocator
(当您无法使用DI容器或框架为您注入它时.lookup
is usually coded in a ServiceLocator
(when you can't have a a DI container or a framework inject it for you).