尝试连接到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接口。
MysqlDataSource
javax.naming.spi.InitialContextFactory
如果您不在容器中,则可以使用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; }