import java.sql.*;//Connection
import javax.sql.*;//DataSource
import javax.naming.*;//Context
public class DatabaseConnection{
private Connection conn = null ;
private String DSNAME="java:comp/env/jdbc/mydatabase" ;
public DatabaseConnection() throws Exception{
Context ctx = new InitialContext() ;
DataSource ds = (DataSource) ctx.lookup(DSNAME);
this.conn = ds.getConnection() ;
}
public Connection getConnection(){
return this.conn ;
}
public void close() throws Exception {
if(this.conn != null){
try{
conn.close() ;
}catch(Exception e){
throw e ;
}
}
}
public static void main(String[] args) throws Exception{
Connection conn = new DatabaseConnection().getConnection();
System.out.println("sucess"+conn);
}
}[/code]老出现错误:
Exception in thread "main" javax.naming.NoInitialContextException: Need to specify class name in env
ironment or system property, or as an applet parameter, or in an application resource file: java.na
ming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at sjy.xg.myc.datasource.DatabaseConnection.<init>(DatabaseConnection.java:11)
at sjy.xg.myc.datasource.DatabaseConnection.main(DatabaseConnection.java:30)