网上很少有关于 WebSphere 根据 jndi 连接 MSSQL的信息.都是连Oracle和db2的多,连MSSQL其实很简单的
现在就写个 jndi 连接 MSSQL 的例子,具体如下
WebSphere 按如上配置后,基本上就没有问题了
然后我们来写Servlet类测试一下.
类如下
package test;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Hashtable;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.omg.CORBA.Context;
/**
* @version 1.0
* @author
*/
public class Mytest extends HttpServlet {
/**
* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
InitialContext ctx = null;
com.microsoft.jdbcx.sqlserver.SQLServerDataSource t = null;
try {
ctx = new InitialContext();
} catch (NamingException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
Connection conn = null;
Hashtable parms = new Hashtable();
parms.put(
InitialContext.INITIAL_CONTEXT_FACTORY,
"com.ibm.websphere.naming.WsnInitialContextFactory");
try {
ctx = new InitialContext(parms);
DataSource ds = (DataSource) ctx.lookup("jdbc/test");
conn = ds.getConnection();
String sql =
"SELECT * FROM CUSTOMER ";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.print(rs.getString("CID")+" "+ rs.getString("USERNAME")+" "+rs.getString("PASSWORD"));
System.out.print("/n");
}
} catch (Exception ne) {
System.out.println(ne);
}
}
/**
* @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
}
看看结果如何:
测试成功,所以websphere操作MSSQL的方法是很多的
有经验的哥们可以一起沟通啊