请教:连接数据库的例子报错问题,请高手点拨一下
我写了一个连接数据库的例子结果总是报错,请高手给看看 郁闷死了,
下面我把 程序代码和报错的内容贴出来,哥哥姐姐们千万给帮个忙,
init err: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
Exception in thread "main " java.lang.NullPointerException
at jdbctest.Jdbc1. <init> (Jdbc1.java:26)
at jdbctest.Jdbc1.main(Jdbc1.java:63)
源码:
package jdbctest;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
import java.util.Properties;
public class Jdbc1 {
public Jdbc1() {
DataSource ds=null;
Context ctx=null;
Connection mycon=null;
try {
ctx=getInitialContext();
ds=(javax.sql.DataSource)ctx.lookup( "dsjdatastore ");
} catch ( Exception e ){
System.out.println( "init err: "+e);
}
Statement mysta=null;
ResultSet myres1=null;
ResultSet myres2=null;
DatabaseMetaData mybase=null;
try {
mycon=ds.getConnection();
mysta=mycon.createStatement();
myres1=mysta.executeQuery( "select * from why ");
while (myres1.next())
{
System.out.println(myres1.getObject(1));
System.out.println();
}
myres1.close();
}catch (SQLException e)
{
System.out.println( "err code : "+e.getErrorCode());
System.out.println( "err message : "+e.getMessage());
}
finally {
try {
if (mysta!=null){
mysta.close();
}
if(mycon!=null)
{
mycon.close();
}
} catch (SQLException e )
{
System.out.println( "err code: "+e.getErrorCode());
System.out.println( "err message: "+e.getErrorCode());
}
}
}
public static void main( String [] args)
{
Jdbc1 test =new Jdbc1();
}
/**
* getInitialContext
*
* @return Context
*/
public static Context getInitialContext() throws Exception {
String url= "t3://localhost:7001 ";
String user= "weblogic ";
String password= "weblogic ";
Properties prop=null;
try {
prop=new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory ");
prop.put(Context.PROVIDER_URL,url);
if(user!=null)
{
prop.put(Context.SECURITY_PRINCIPAL,user);
prop.put(Context.SECURITY_CREDENTIALS,password==null ? " ":password);
}
return new InitialContext (prop);
}catch (Exception e ){
throw e ;
}
}
}
[解决办法]
try {
ctx=getInitialContext();
ds=(javax.sql.DataSource)ctx.lookup( "dsjdatastore ");
}
改成:
try {
ctx=new InitialContext();
ds=(javax.sql.DataSource)ctx.lookup( "dsjdatastore ");
就ok了