JDBC Datasource mit Datenbank verbinden

applejoe

applejoe

Mitglied
Thread Starter
Dabei seit
29.10.2005
Beiträge
57
Reaktionspunkte
0
Ich arbeite gerade das Buch "Datenbanken & Java" von Saake/Sattler durch. In Kapitel Kapitel 4.3.1 wird die Verwendung von Datenquellen (DataSource) statt des Treibermanagers (DriverManager) beschrieben. Die einzelnen Schritte sind zwar grob beschrieben, es ist aber leider kein Beispielcode einer kleinen Anwendung gegeben. Habe also selber mal was versucht. Funktioniert aber nicht. In der Zeile
Code:
initialCtx.bind("jdbc/BuchDB", mySqlDs);
bricht der try-Block mit der Meldung
NamingException: 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
ab
In der Zeile
Code:
conWithDataSource = ds.getConnection("root", "root");
gibt es dann eine NullPointerException. In Foren finde ich wenig über das DataSource Konzept. Da ist meistens der DriverManger Thema. Hat jemand ne Idee?

Code:
public class dbds {
    public static void main(String[] args) {       
        Context initialCtx;       
        Connection conWithDataSource = null;
        DataSource ds = null;
        Statement stmt;
        ResultSet rs;
        String query = "Select title, price, stock FROM book";       
        MysqlDataSource mySqlDs = new MysqlDataSource();
        mySqlDs.setServerName("localhost");
        mySqlDs.setDatabaseName("myDB");
        mySqlDs.setPortNumber(8889);
        try {
            initialCtx = new InitialContext();
            initialCtx.bind("jdbc/BuchDB", mySqlDs);
            // Das war der Eintrag in den Namensdienst
            // Und jetzt Verbindung über diesen Eintrag herstellen
            Context connectionCtx = new InitialContext();
            ds = (DataSource) connectionCtx.lookup("jdbc/BuchDB");
           
        } catch (NamingException exc) {
            System.out.println("NamingException: " + exc.getMessage());
        }
        try {
            conWithDataSource = ds.getConnection("root", "root");
            stmt = conWithDataSource.createStatement();
            rs = stmt.executeQuery(query);               
       
            while (rs.next()) {
                String s = rs.getString(1);
                double d = rs.getDouble(2);
                int i = rs.getInt(3);
                System.out.println(s + ", " + d + " EURO, " + i);
            }           
        } catch (SQLException exc){
            System.out.println("SQLExeption" + exc.getMessage());
        }   
    }
}
 
Hast Du im Ordner jdbc ein File namens "BuchDB.properties" liegen?

Ich vermute nicht.
Zumindest legt die Fehlermeldung das nahe ...
 
Ne, habe ich nicht. ich habe gar kein File "BuchDB.properties" irgendwo liegen. Ich fürchte ich habe die Funktionsweise dieses Namensdienst noch überhaupt nicht verstanden. Aus der Beschreibung der API werde ich nicht schlau. Kennst du irgendeine Quelle, wo das gut beschrieben ist?
 
Ich glaube du musst dich eher um JNDI kümmern.

Kannst ja mal hier schauen:
http://java.sun.com/products/jndi/tutorial/index.html

Nachtrag:
So, ich habe mal einwenig über JNDI gelesen (hatte mich jetzt auch interessiert). Ich denke du musst in jedem Fall eine INITIAL_CONTEXT_FACTORY angeben, weil sonst keine vorhanden ist und das bekommt man über die Meldung "NamingException: 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" gesagt.

Ich habe mal dein Beispiel etwas erweitert. Jetzt wird eine InitialContextFactory erzeugt, die wiederum ein eigenes Context-Objekt erzeugt.
(Ich habe sehr, sehr wenig Ahnung von JNDI, ob das also im Gesamtkonzept von JNDI Sinn macht weiß ich nicht, aber es funktioniert erstmal...)

Code:
package de.oglimmer;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;
import javax.sql.DataSource;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

public class Test {

    private static DataSource getDS() {
        MysqlDataSource mySqlDs = new MysqlDataSource();
        mySqlDs.setServerName("localhost");
        mySqlDs.setDatabaseName("test");
        mySqlDs.setUser("root");
        mySqlDs.setPassword("");
        // mySqlDs.setPortNumber(8889);
        return mySqlDs;
    }

    public static void main(String[] args) {

        try {
            DataSource ds = null;
            try {
                Hashtable env = new Hashtable();
                env.put(Context.INITIAL_CONTEXT_FACTORY, "de.oglimmer.Test$MyContextFactory");

                Context initialCtx = new InitialContext(env);
                initialCtx.bind("jdbc/BuchDB", getDS());

                Context connectionCtx = new InitialContext(env);
                ds = (DataSource) connectionCtx.lookup("jdbc/BuchDB");

            }
            catch (NamingException exc) {
                exc.printStackTrace();
                System.exit(0);
            }

            Connection conWithDataSource = ds.getConnection();
            Statement stmt = conWithDataSource.createStatement();
            ResultSet rs = stmt.executeQuery("Select title, price, stock FROM book");

            while (rs.next()) {
                String s = rs.getString(1);
                double d = rs.getDouble(2);
                int i = rs.getInt(3);
                System.out.println(s + ", " + d + " EURO, " + i);
            }
        }
        catch (SQLException exc) {
            exc.printStackTrace();
        }
    }

    public static class MyContextFactory implements InitialContextFactory {

        private static MyContext c = new MyContext();

        public Context getInitialContext(Hashtable environment) throws NamingException {
            return c;
        }

    }

}

class MyContext implements Context {

    private Map data = new HashMap();

    public Object addToEnvironment(String propName, Object propVal) throws NamingException {
        return null;
    }

    public void bind(Name name, Object obj) throws NamingException {
        data.put(name, obj);
    }

    public void bind(String name, Object obj) throws NamingException {
        data.put(name, obj);
    }

    public void close() throws NamingException {
    }

    public Name composeName(Name name, Name prefix) throws NamingException {
        return null;
    }

    public String composeName(String name, String prefix) throws NamingException {
        return null;
    }

    public Context createSubcontext(Name name) throws NamingException {
        return null;
    }

    public Context createSubcontext(String name) throws NamingException {
        return null;
    }

    public void destroySubcontext(Name name) throws NamingException {
    }

    public void destroySubcontext(String name) throws NamingException {
    }

    public Hashtable<?, ?> getEnvironment() throws NamingException {
        return null;
    }

    public String getNameInNamespace() throws NamingException {
        return null;
    }

    public NameParser getNameParser(Name name) throws NamingException {
        return null;
    }

    public NameParser getNameParser(String name) throws NamingException {
        return null;
    }

    public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
        return null;
    }

    public NamingEnumeration<NameClassPair> list(String name) throws NamingException {
        return null;
    }

    public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
        return null;
    }

    public NamingEnumeration<Binding> listBindings(String name) throws NamingException {
        return null;
    }

    public Object lookup(Name name) throws NamingException {
        return data.get(name);
    }

    public Object lookup(String name) throws NamingException {
        return data.get(name);
    }

    public Object lookupLink(Name name) throws NamingException {
        return null;
    }

    public Object lookupLink(String name) throws NamingException {
        return null;
    }

    public void rebind(Name name, Object obj) throws NamingException {
    }

    public void rebind(String name, Object obj) throws NamingException {
    }

    public Object removeFromEnvironment(String propName) throws NamingException {
        return null;
    }

    public void rename(Name oldName, Name newName) throws NamingException {
    }

    public void rename(String oldName, String newName) throws NamingException {
    }

    public void unbind(Name name) throws NamingException {
    }

    public void unbind(String name) throws NamingException {
    }

}
 
Zuletzt bearbeitet:
Zurück
Oben Unten