javax.naming.NoInitialContextException with mysql DataSource

前端 未结 1 1116
野的像风
野的像风 2021-01-26 02:25

Trying to connect to a MySQL database

MysqlDataSource mysqlDs = new MysqlDataSource();
Properties prop = new Properties();
String mysqlDataSourceDriver = \"com.m         


        
相关标签:
1条回答
  • 2021-01-26 03:03

    This is because MysqlDataSource is not implementing javax.naming.spi.InitialContextFactory interface.

    If you are not in a container you can use rmi registry. Something like:

    try{
      startRegistry();
      InitialContext context = createContext();
      MysqlDataSource mysqlDs = new MysqlDataSource();
      context.rebind("jdbc/wczasy", mysqlDs);
    } catch (Exception e) {
      System.out.println("Error while binding: " + e.getMessage());
      e.printStackTrace();
    }
    
    
    private static void startRegistry() throws RemoteException {
      LocateRegistry.createRegistry(1099);
      System.out.println("RMI registry ready.");
    }
    
    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;
    }
    
    0 讨论(0)
提交回复
热议问题