Configuring MySQL DataSources

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Configuring MySQL DataSources

This Java example program shows how to configure MySQL DataSource.

[edit] Java Source Code

  • Package: example.mysql
  • File: SetupJNDIDataSource.java
package example.mysql;
 
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.util.Properties;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.ConnectionPoolDataSource;
 
public class SetupJNDIDataSource {
    public static void main(String args[]) {
	if (args.length < 2) {
	    System.out.println("usage: SetupJNDIDataSource username password");
	    return;
	}
 
	try {
	    startRegistry();
 
	    ConnectionPoolDataSource dataSource = createDataSource(args[0], args[1]);
 
	    InitialContext context = createContext();
	    context.rebind("HrDS", dataSource);
 
	} catch (Exception e) {
	    System.out.println("SetupJNDIDataSource err: " + e.getMessage());
	    e.printStackTrace();
	}
    }
 
    private static void startRegistry() throws RemoteException {
	LocateRegistry.createRegistry(1099);
	System.out.println("RMI registry ready.");
    }
 
    private static ConnectionPoolDataSource createDataSource(String username, String password) {
	MysqlConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
	dataSource.setUser(username);
	dataSource.setPassword(password);
	dataSource.setServerName("localhost");
	dataSource.setPort(3306);
	dataSource.setDatabaseName("chapter04_jdbc21");
	return dataSource;
    }
 
    private static InitialContext createContext() throws NamingException {
	Properties env = new Properties();
	env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
	env.put(Context.PROVIDER_URL, "rmi://localhost:1099");
	InitialContext context = new InitialContext(env);
	return context;
    }
}

[edit] What Result You Can Get

Run the program, you will get:

usage: SetupJNDIDataSource username password

[edit] Required External Libraries and/or Files for this Java Example

Need nothing.

http://www.ase2009.com/ online casino 132 http://www.hellzyea.com/health health insurance 8DDD http://www.yourautoinsurancesite.com/ auto insurance quotes 135811 http://www.makemeasammich.com/ auto insurance mcnxu

[edit] Question & Answer

Any question?

Click edit and post your question or answer here.


Personal tools