<!-- MSSQLserver dB username and password for dB connections --> <parameter> <name>username</name> <value>sa</value> </parameter> <parameter> <name>password</name> <value></value> </parameter>
<!-- Class name for mssqlserver JDBC driver --> <parameter> <name>driverClassName</name> <value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value> </parameter>
<!-- The JDBC connection url for connecting to your mssqlserver dB.--> <parameter> <name>url</name> <value>jdbc:microsoft:sqlserver://localhost:1433;databasename=Northwind</value> </parameter> </ResourceParams> </Context>
注意:我本地的数据库的sa的密码为空,数据库使用的是Northwind,我的目录名DBTest,他的目录是D:\rautinee work\db\
打开DBTest下面的web.xml文件,用下面的代码替换原来的内容
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <description>MSSql server 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>
ok,配置完成,下面的工作是需要编写两个文件测试一下,连接是否成功。
这里我用了http://jakarta.apache.org上面的例子
首先是bean文件
package foo;
import javax.naming.*; import javax.sql.*; import java.sql.*;
public class DBTest {
String foo = "Not Connected"; int bar = -1; public void init() { try{ Context ctx = new InitialContext(); if(ctx == null ) throw new Exception("Boom - No Context");
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/TestDB");
if (ds != null) { Connection conn = ds.getConnection(); if(conn != null) { foo = "Got Connection "+conn.toString(); Statement stmt = conn.createStatement(); ResultSet rst = stmt.executeQuery("select * from orders"); if(rst.next()) { foo=rst.getString("CustomerID"); bar=rst.getInt("OrderID"); } conn.close(); } } }catch(Exception e) { e.printStackTrace(); } } |