81,092
社区成员
发帖
与我相关
我的任务
分享
package test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class GetConnectionTest {
public static void main(String[] args) {
GetConnectionTest.show();
}
public static String show(){
InitialContext ctx;
PreparedStatement pstmt = null;
Connection conn = null;
String sql = "select * from user";
String show = null;
try {
ctx = new InitialContext();
/*
* 在下面的字符串"java:comp/env/jdbc/course"中,*"java:comp/env/"是不变的,
* 而"jdbc/course"大家应该还记得自己之前起的数据源名称吧!
*/
//DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/TestDB");
Context context = (Context)ctx.lookup("java:comp/env/");
DataSource ds = (DataSource)context.lookup("jdbc/TestDB");
conn = ds.getConnection();
System.out.println("got conn");
pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
rs.last();
System.out.println("row:" + rs.getRow());
rs.first();
show = rs.getString(2) +"||" +rs.getInt(3);
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return show;
}
}
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(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at test.GetConnectionTest.show(GetConnectionTest.java:30)
at test.GetConnectionTest.main(GetConnectionTest.java:14)