Java Tomcat6 MySql JDBC数据源配置
我一直使用Spring的依赖注入来获取数据源对象并在DAO中使用它们,但现在,我不得不编写一个没有这些的应用程序 用Spring,我可以写这样的东西:Java Tomcat6 MySql JDBC数据源配置,java,mysql,tomcat,jdbc,datasource,Java,Mysql,Tomcat,Jdbc,Datasource,我一直使用Spring的依赖注入来获取数据源对象并在DAO中使用它们,但现在,我不得不编写一个没有这些的应用程序 用Spring,我可以写这样的东西: <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /&g
<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中使用datasource呢?我只使用servlet和JSP。性能是非常重要的因素 您可以将数据源声明为JNDI对象,并通过JNDI查找检索数据源:
DataSource ds = (DataSource)
envCtx.lookup("jdbc/EmployeeDB");
如文件所述,并且
这是你能得到的最基本的东西,因此从那以后,性能完全取决于你。信不信由你,人们在Spring之前编写应用程序,有些人仍然没有使用:)在你的情况下,你可以使用Tomcat连接池(在中有一个完整的MySQL配置示例)。让我总结一下: 首先,将驱动程序放入
$CATALINA_HOME/lib
然后,在Tomcat中配置JNDI数据源,方法是将资源声明添加到:
并在应用程序中使用JNDI查找获取数据源:
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();
请注意,这样的
查找通常是在一个中编码的(当您不能有DI容器或框架为您注入它时)。我曾经在sybase中遇到错误,我在WebContent文件夹中缺少META-INF文件夹。将context.xml放在该位置修复了错误,无法为连接URL“null”创建类“”的JDBC驱动程序。。。
//www.abbulkmailer.com
我的context.xml看起来像
<Context path="/reports" docBase="reports" debug="5" reloadable="true" crossContext="true">
<Resource name='jdbc/ASCSybaseConnection'
auth='Container'
type='javax.sql.DataSource'
username='fdd'
password='555'
driverClassName='com.sybase.jdbc2.jdbc.SybDriver'
maxActive='100'
maxIdle='100'
minIdle='10'
removeAbandoned="true"
removeAbandonedTimeout="60"
testOnBorrow="true"
logAbandoned="true"
url='jdbc:sybase:Tds:1.3.4.5:654/DB'/>
</Context>
我无法理解为什么这件事没有至少一次投票。@BalusC:该死,我永远也得不到那枚无名英雄徽章!当然只是开玩笑,非常感谢。哈哈。你必须要有一个好主意。@BalusC如果发生这种情况,我就辞职@PascalThivent哪个位置更适合于上下文文件
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();
<Context path="/reports" docBase="reports" debug="5" reloadable="true" crossContext="true">
<Resource name='jdbc/ASCSybaseConnection'
auth='Container'
type='javax.sql.DataSource'
username='fdd'
password='555'
driverClassName='com.sybase.jdbc2.jdbc.SybDriver'
maxActive='100'
maxIdle='100'
minIdle='10'
removeAbandoned="true"
removeAbandonedTimeout="60"
testOnBorrow="true"
logAbandoned="true"
url='jdbc:sybase:Tds:1.3.4.5:654/DB'/>
</Context>