1. start MySQL server. If a
test
database is not present, create it (inside mysql console, run create database test;
)2. put MySQL Connector/J jar (mysql-connector-java-5.0.3-bin.jar) in
%JBOSS_HOME%\server\default\lib
3. back up and edit
%JBOSS_HOME%\docs\examples\jca\mysql-ds.xml
...Set
<jndi-name>jdbc/mysql</jndi-name>
<use-java-context>false</use-java-context>
<connection-url>jdbc:mysql://localhost:3306/test</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>root</user-name>
<password></password>
...
use-java-context
to false. This tells JBoss to open this datasource for remote access, and its JNDI name will be used for remote lookup without using java:/
prefix.4. copy modified mysql-ds.xml to
%JBOSS_HOME%\server\default\deploy
5. code java client:
package com.foo;To compile it:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DataSourceTest {
public static void main(String[] args) throws Exception {
testDataSource();
}
private static void testDataSource()
throws NamingException, SQLException {
final String sql = "select version()";
InitialContext ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup("jdbc/mysql");
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
con = ds.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()) {
System.out.println("Query '" + sql + "' returned " + rs.getString(1));
}
} finally {
if(rs != null) rs.close();
if(stmt != null) stmt.close();
if(con != null) con.close();
}
}
}
C:\ws\nb\scrap\src\com\foo>6. create a
javac -d C:\ws\nb\scrap\build\classes DataSourceTest.java
jndi.properties
and put it in classpath (C:\ws\nb\scrap\build\classes
):java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory7. run it with JDK 6 so that I can use wildcard (*) in classpath and don't have to figure out which jboss jars to include (see my previous post on this feature):
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=jnp://localhost:1099
java -cp C:\ws\nb\scrap\build\classes;%JBOSS_HOME%\lib\*;%JBOSS_HOME%\server\default\lib\* com.foo.DataSourceTest
Query 'select version()' returned 5.0.18
Tags: