gpt4 book ai didi

javax.naming.NoInitialContextException 与 mysql 数据源

转载 作者:行者123 更新时间:2023-11-29 08:18:40 27 4
gpt4 key购买 nike

尝试连接到 MySQL 数据库

MysqlDataSource mysqlDs = new MysqlDataSource();
Properties prop = new Properties();
String mysqlDataSourceDriver = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource";
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, mysqlDataSourceDriver);
properties.put(Context.PROVIDER_URL , "jdbc:mysql://localhost:3306/database");
Context ctx = new InitialContext(prop);
ctx.bind("jdbc/wczasy", mysqlDs);

以及堆栈跟踪:

javax.naming.NoInitialContextException: Need to specify class name in environment or     system property, or as an applet parameter, or in an application resource file:      java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:344)
at javax.naming.InitialContext.bind(InitialContext.java:419)
at src.wczasy.database.Connector.connect(Connector.java:53)
at src.wczasy.Wczasy.main(Wczasy.java:10)

由以下行引起:ctx.bind("jdbc/wczasy", mysqlDs);我被困住了,有人能帮我吗?谢谢。

最佳答案

这是因为 MysqlDataSource 没有实现 javax.naming.spi.InitialContextFactory 接口(interface)。

如果您不在容器中,您可以使用 rmi 注册表。像这样的东西:

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;
}

关于javax.naming.NoInitialContextException 与 mysql 数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20016503/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com