- Java code
import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import javax.sql.DataSource;import javax.naming.Context;import javax.naming.InitialContext;import javax.naming.*;import java.sql.SQLException;import java.util.Properties;import java.util.List;import java.util.ArrayList;import java.util.Iterator;import myjdbc.util.WrapperUtil;public class DatabaseOperation { private static DatabaseOperation dbo = null; private static final int FETCH_ALL = Integer.MAX_VALUE; private static final int NO_OFFSET = -1; private static final int DEFAULT_PAGE_SIZE = 20; private Connection conn = null; private PreparedStatement pst = null; private ResultSet rs = null; private DataSource ds = null; private static String staticTableConfigPath = "src/conf"; // private static String staticDataSourceName = "DataSource"; //私有构在函数 private DatabaseOperation() { try { Context ctx = getWeblogicServerInitialContext(); ds = (DataSource) ctx.lookup(staticDataSourceName); } catch (NamingException ex) { ex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } //获得weblogic的上下文 private final Context getWeblogicServerInitialContext() throws Exception { String url = "t3://127.0.0.1:7001"; String user = null; String password = null; Properties properties; try { properties = new Properties(); // properties.put("tableConfigPath","F:/jbuilder_project/writebook/relation_manage/src/conf"); properties.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory"); properties.put(Context.PROVIDER_URL, url); if (user != null) { properties.put(Context.SECURITY_PRINCIPAL, user); properties.put(Context.SECURITY_CREDENTIALS, password == null ? "" : password); } return new javax.naming.InitialContext(properties); } catch (Exception e) { e.printStackTrace(); throw e; } }private void openConnection() { if (conn == null) { try { conn = ds.getConnection(); } catch (SQLException e) { e.printStackTrace(); } } } public static void main(String args[]) throws Exception { List result = new ArrayList(); String sql = "select * from orderitem as a";// sql = sql.toLowerCase(); DatabaseOperation database = DatabaseOperation.getInstance(); // database.openConnection(); result = database.executeSQL(sql); System.out.println("asdf=====>" + result.size());
测试出现了错误
java.lang.NullPointerException
at myjdbc.DatabaseOperation.openConnection(DatabaseOperation.java:88)
at myjdbc.DatabaseOperation.getTotalPage(DatabaseOperation.java:182)
at test.TestDatabaseOperation.testGetTotalPage(TestDatabaseOperation.java:25)
...(Click for full stack trace)...
------解决方案--------------------------------------------------------
可能这里错了 result = database.executeSQL(sql);
System.out.println("asdf=====>" + result.size());
改成
if(result.next())
{System.out.println("asdf=====>" + result.size());
}
看看
------解决方案--------------------------------------------------------
看看你的 DataSource 设置,感觉是没有找到 "staticDataSourceName".