简体   繁体   中英

JNDI connection pooling for a console program?

I'm trying to connect with a database connection pool :

thufir@dur:~$ 
thufir@dur:~$ java -jar NetBeansProjects/Dialer/dist/Dialer.jar 
hello world
Jun 23, 2014 1:04:39 AM net.bounceme.dur.Dialer <init>
INFO: {dur.reports.db.jndi.name=jdbc/vehicles, dur.db.jndi.name=jdbc/vehicles, dur.reports.db.type=MYSQL, reports.exportRawData=true, dur.db.type=MYSQL}
Jun 23, 2014 1:04:39 AM net.bounceme.dur.Dialer <init>
SEVERE: null
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.lookup(InitialContext.java:411)
    at net.bounceme.dur.Connector.<init>(Connector.java:15)
    at net.bounceme.dur.Dialer.<init>(Dialer.java:19)
    at net.bounceme.dur.Dialer.main(Dialer.java:26)

thufir@dur:~$ 

I thought it was possible to use JNDI and connection pooling for a console app, without Tomcat, Glassfish or similar?

package net.bounceme.dur;

import java.sql.SQLException;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class Connector {


    public Connector(Properties props) throws NamingException, SQLException {
        InitialContext ctx = new InitialContext();
        //ctx.lookup(null); //????????
        DataSource ds = (DataSource) ctx.lookup(props.getProperty("dur.db.jndi.name"));
    }

}

Or, is it an absolute requirement to use some sort of server or container?

Getting naming services and DataSource (with a connection from a pool) is a container based service. This is why you get this exception (there is no IntialContext available because there is no service available to provide it). You will need a container of some kind to provide these services.

You can always write your own connection pool logic, but you will be doing it from the start.

You can also connect to a remote server to get the InitialContext and additional services, but I would guess that is not what you are asking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM