1、mssql-ds.xml的配置
<datasources>
<local-tx-datasource>
<jndi-name>MSSQLDS</jndi-name>
<use-java-context>false</use-java-context>
<connection-url>jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=CHDPSDB</connection-url>
<driver-class>com.microsoft.jdbc.sqlserver.SQLServerDriver</driver-class>
<user-name>sa</user-name>
<password>xiaoquan</password>
<metadata>
<type-mapping>MS SQLSERVER2000</type-mapping>
</metadata>
</local-tx-datasource>
</datasources>
2、实例调用
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.util.Properties;
import java.util.Hashtable;
import java.sql.*;
public class DBCon {
public static void main(String[] args) throws NamingException, SQLException {
Properties props = new Properties();
props.setProperty("java.naming.factory.initial",
"org.jnp.interfaces.NamingContextFactory");
props.setProperty("java.naming.provider.url", "localhost:1099");
props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");
InitialContext ctx = new InitialContext(props);
DataSource ds = (DataSource) ctx.lookup("MSSQLDS");
Connection conn = ds.getConnection();
Statement stat = conn.createStatement();
String sql = "select * from chd_staff";
ResultSet rs = stat.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1));
}
rs.close();
stat.close();
conn.close();
System.out.print("End");
}
}
3、异常处理
如出现以下异常:
Cannot instantiate class: org.jnp.interfaces.NamingContextFactory [Root exception is java.lang.ClassNotFoundException: org.jnp.interfaces.NamingContextFactory]
请查看是否将JBOSS_Home下client文件夹中的所有jar包都导入到了项目工程中。
实际上,在classpath內,加上%JBoss Home%clientjbossall-client.jar就可以了