Database access code prob
Hi there, can anyone see if there is anything wrong with the code below. I can see that the variables have values when outputting to dos but I keep getting a NullPointerException. Any ideas why?
Error:
Exception in thread "main" java.lang.NullPointerException
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:130)
at com.javacomponents.DBConnection.getConnection(DBConnection.java:35)
at com.javacomponents.testDBConn.main(testDBConn.java:13)
Press any key to continue . . .
code with static main method:
import java.sql.*;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class testDBConn{
public static void main(String args[]){
try{
Connection connection=DBConnection.getConnection();
Statement statement = connection.createStatement();
String query = "select * from users";
ResultSet rs = statement.executeQuery(query);
while(rs.next()){
System.out.println(rs.getString(1));
statement.close();
connection.close();
}catch(SQLException SQLe){
System.out.println("SQL Error "+SQLe.getMessage());
}DB Connection class
import java.sql.*;
public class DBConnection {
private static String username = null;
private static String password = null;
private static String dbURL = null;
private static String driver = null;
private static Connection connection = null;
public static void setUsername (String val) {
username = val;
public static void setPassword (String val) {
password = val;
public static void setDbURL (String val) {
dbURL = val;
public static void setDriver (String val) {
driver = val;
System.out.println("driver = "+driver);
public static Connection getConnection () {
if (connection != null) return connection;
try {
Class.forName( driver ); // load the JDBC "driver" class
connection = DriverManager.getConnection( dbURL, username, password ); // get connection
return connection;
} catch ( ClassNotFoundException e ) {
System.out.println("in ClassNotFoundException");
return null;
} catch ( SQLException e ){
System.out.println("in SQLException");
return null;
}
In the contextInitialized you have not created an instance of DBConnection! you've just called some static methods of this latter class.
If you want to create a DBConnection instance in the contextInitialized method, so use singleton pattern like the following:
import java.sql.*;
public class DBConnection {
private static Connection connection = null;
private static DBConnection instance = null;
private static String driver;
private static String dbURL;
private static String username;
private static String password;
private DBConnection() {
public static String getDbURL() {
return dbURL;
public static void setDbURL(String dbURL) {
DBConnection.dbURL = dbURL;
public static String getDriver() {
return driver;
public static void setDriver(String driver) {
DBConnection.driver = driver;
public static String getPassword() {
return password;
public static void setPassword(String password) {
DBConnection.password = password;
public static String getUsername() {
return username;
public static void setUsername(String username) {
DBConnection.username = username;
public synchronized final static DBConnection getInstance() {
return (instance == null) ? new DBConnection() : instance;
public static Connection getConnection() throws Exception{// you can remove throws Exception
if(connection == null){
throw new Exception("The DB connection may have not been initialized");//you can return null instead
createConnection();
return connection;
private static void createConnection() {
try {
Class.forName(driver); // load the JDBC "driver" class
connection = DriverManager.getConnection(dbURL, username, password); // get connection
} catch (ClassNotFoundException e) {
System.out.println("in ClassNotFoundException");
} catch (SQLException e) {
System.out.println("in SQLException");
}You should then do this :
DBConnection instance = DBConnection.getInstance(driver, dbURL, username,
password);
instance .setUsername (username);
instance .setPassword (password);
instance .setDbURL (dbURL);
instance .setDriver (driver);instead of : DBConnection.setUsername (username);
DBConnection.setPassword (password);
DBConnection.setDbURL (dbURL);
DBConnection.setDriver (driver);hth
Message was edited by:
java_2006
Similar Messages
-
Database access code in objects constructor, or in data access object
Given an object that is stored in a database, is it better to have the database access code in a constructor method, or a data access layer object? E.g. I have a Person class
public class Person{
int Id;
String name;
int age;
}When I want to read a person's details from the database, I could use a constructor something like this:
public Person(int id){
Connection con = getDatabaseConnection();
ResultSet rs = con.createStatement().executeQuery("Select name, age from person where person_id = " + id);
rs.next();
this.name = rs.getString(1);
this.age=rs.getInt(2);
}Or I could use a method in a data access object :
public Person getPerson(int id){
Person p = new Person();
Connection con = getDatabaseConnection();
ResultSet rs = con.createStatement().executeQuery("Select name, age from person where person_id = " + id);
rs.next();
p.setName(rs.getString(1));
p.setAge(rs.getInt(2));
return p;
}It seems to me that the constructor approach has two advantages
(1) the SQL code is kept in the relevant class (so if I want to add a field to Person, I only have to make changes to the Person class)
(2) I don't have to have a setter method for each field
Is one or other of these ways generally recognized as 'best practise'?malcolmmc wrote:
But then, on the other hand, everytime a Person gains a new field that's two places you have to change it. if the persistence interface is written in terms of the object and uses ORM, I don't have to touch the implementation. all i have to do is update the object, the database, and the mapping - just like you and your home brew ORM.
besides, so what? i'd fear the resource leak, bad layering, more difficult testing more.
Actually lately I've used annotations to label setters with database field names and run a simple home brew ORM to convert rows into objects even when not using a more complex persistence manager.home brew ORM? why is that necessary when you can choose from hibernate, ibatis, jdo, jpa, etc.? that's just nuts.
% -
Database access in a MVC architecture
Hi!
I'm a bit confused with regards to where the database access code should be put in a MVC architecture. From reading various articles and posts on this forum, there seem to be a lot of different opinions.
Some seem to put the database access code in the controller servlet(or JSP), while some seem to use helper classes from the JavaBeans, while a few people even seem to access the database directly from the JavaBean.
My questions is: What is the best place to put the database stuff in a MVC architecture? An explanation as to why a particular solution is the best would be great..
Thanks!
regards,
VidarLet's say I have a class called Department that contains methods like getName(), getId(), setName(), etc... The Department class is my business object. To save and load Departments from a database, I have a class called DepartmentManager. The DepartmentManager saves and loads the departments to the database, and has methods like saveDepartment(), saveDepartments(), loadDepartment(), getDepartments(), etc... In some cases, my manager classes also caches the results so they don't have to load from the database each time. Often times, the manager class is a singleton. My Department class has no idea how it is persisted, or that it is part of a cache. It just knows about itself. The DepartmentManager is resonsible for managing all the persistance and lookup functionality for Departments.
Therefore, if I have a JSP page that needs to display Departments, my code might look like:
DepartmentManager dm = DepartmentManager.getManager();
ArrayList listDepartments = dm.getDepartmentList();
for (int i = 0; listDepartments != null && i < listDepartments.size(); i++) {
Department dept = (Department)listDepartments.get(i);
out.println("<option value=\"" + dept.getId() + "\">" + dept.getName());
}If I had a specific Department I needed, I would get it as follows:
DepartmentManager dm = DepartmentManager.getManager();
Department dept = dm.getDepartment(nId); -
Regarding Provisioning a user to Database Access Tables
Hi,
I've just completed with the installation of OIM 9101 and upgradation of 9101 to 9102. I'm facing a bit wierd. When I try to create a GTC for the Database Access Tables, I'm not able to see Database Access Tables option, in the drop down list for the Transport Provider.
I'm a bit confused if I've wrongly upgraded the system or if at all i've missed out some step. Though OIM seems to be ok and working fine.
Any suggestions as to how to solve this ?
Regards
NikhilThanks Prakash,
The issue has been resolved.
I'd like a bit more of your help. I'm facing an error as follows :
2011-04-14 12:21:52,074 ERROR [XELLERATE.GC.PROVIDER.TRANSFORMATION] Could not transform the data
java.lang.NullPointerException
at com.thortech.xl.gc.util.TransformationEngine.doTransformation(Unknown Source)
at com.thortech.xl.gc.util.TransformationEngine.transform(Unknown Source)
at com.thortech.xl.gc.runtime.GCAdapterLibrary.executeFunctionality(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.thortech.xl.adapterGlue.ScheduleItemEvents.adpDBAT_PROVISIONING1_GTC.GENERICADAPTER(adpDBAT_PROVISIONING1_GTC.java:125)
at com.thortech.xl.adapterGlue.ScheduleItemEvents.adpDBAT_PROVISIONING1_GTC.implementation(adpDBAT_PROVISIONING1_GTC.java:70)
at com.thortech.xl.client.events.tcBaseEvent.run(Unknown Source)
at com.thortech.xl.dataobj.tcDataObj.runEvent(Unknown Source)
at com.thortech.xl.dataobj.tcScheduleItem.runMilestoneEvent(Unknown Source)
at com.thortech.xl.dataobj.tcScheduleItem.eventPostInsert(Unknown Source)
at com.thortech.xl.dataobj.tcDataObj.insert(Unknown Source)
at com.thortech.xl.dataobj.tcDataObj.save(Unknown Source)
at com.thortech.xl.dataobj.tcORC.insertNonConditionalMilestones(Unknown Source)
at com.thortech.xl.dataobj.tcORC.completeSystemValidationMilestone(Unknown Source)
at com.thortech.xl.dataobj.tcOrderItemInfo.completeCarrierBaseMilestone(Unknown Source)
at com.thortech.xl.dataobj.tcOrderItemInfo.eventPostInsert(Unknown Source)
at com.thortech.xl.dataobj.tcUDProcess.eventPostInsert(Unknown Source)
at com.thortech.xl.dataobj.tcDataObj.insert(Unknown Source)
at com.thortech.xl.dataobj.tcDataObj.save(Unknown Source)
at com.thortech.xl.dataobj.tcTableDataObj.save(Unknown Source)
at com.thortech.xl.ejb.beansimpl.tcFormInstanceOperationsBean.setProcessFormData(Unknown Source)
at com.thortech.xl.ejb.beansimpl.tcFormInstanceOperationsBean.setProcessFormData(Unknown Source)
at com.thortech.xl.ejb.beans.tcFormInstanceOperationsSession.setProcessFormData(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.invocation.Invocation.performCall(Invocation.java:359)
at org.jboss.ejb.StatelessSessionContainer$ContainerInterceptor.invoke(StatelessSessionContainer.java:237)
at org.jboss.resource.connectionmanager.CachedConnectionInterceptor.invoke(CachedConnectionInterceptor.java:158)
at org.jboss.ejb.plugins.StatelessSessionInstanceInterceptor.invoke(StatelessSessionInstanceInterceptor.java:169)
at org.jboss.ejb.plugins.CallValidationInterceptor.invoke(CallValidationInterceptor.java:63)
at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInterceptor.java:121)
at org.jboss.ejb.plugins.TxInterceptorCMT.runWithTransactions(TxInterceptorCMT.java:350)
at org.jboss.ejb.plugins.TxInterceptorCMT.invoke(TxInterceptorCMT.java:181)
at org.jboss.ejb.plugins.SecurityInterceptor.invoke(SecurityInterceptor.java:168)
at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:205)
at org.jboss.ejb.plugins.ProxyFactoryFinderInterceptor.invoke(ProxyFactoryFinderInterceptor.java:138)
at org.jboss.ejb.SessionContainer.internalInvoke(SessionContainer.java:648)
at org.jboss.ejb.Container.invoke(Container.java:960)
at sun.reflect.GeneratedMethodAccessor128.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.invocation.local.LocalInvoker$MBeanServerAction.invoke(LocalInvoker.java:169)
at org.jboss.invocation.local.LocalInvoker.invoke(LocalInvoker.java:118)
at org.jboss.invocation.InvokerInterceptor.invokeLocal(InvokerInterceptor.java:209)
at org.jboss.invocation.InvokerInterceptor.invoke(InvokerInterceptor.java:195)
at org.jboss.proxy.TransactionInterceptor.invoke(TransactionInterceptor.java:61)
at org.jboss.proxy.SecurityInterceptor.invoke(SecurityInterceptor.java:70)
at org.jboss.proxy.ejb.StatelessSessionInterceptor.invoke(StatelessSessionInterceptor.java:112)
at org.jboss.proxy.ClientContainer.invoke(ClientContainer.java:100)
at $Proxy769.setProcessFormData(Unknown Source)
at Thor.API.Operations.tcFormInstanceOperationsClient.setProcessFormData(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at Thor.API.Base.SecurityInvocationHandler$1.run(Unknown Source)
at Thor.API.Security.LoginHandler.jbossLoginSession.runAs(Unknown Source)
at Thor.API.Base.SecurityInvocationHandler.invoke(Unknown Source)
at $Proxy813.setProcessFormData(Unknown Source)
at com.thortech.xl.webclient.actions.DirectProvisionUserAction.handleVerifyProcessData(Unknown Source)
at com.thortech.xl.webclient.actions.DirectProvisionUserAction.goNext(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:280)
at com.thortech.xl.webclient.actions.tcLookupDispatchAction.execute(Unknown Source)
at com.thortech.xl.webclient.actions.tcActionBase.execute(Unknown Source)
at com.thortech.xl.webclient.actions.tcAction.execute(Unknown Source)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.thortech.xl.webclient.security.SecurityFilter.doFilter(Unknown Source)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:182)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446)
at java.lang.Thread.run(Thread.java:619)
2011-04-14 12:21:52,074 ERROR [XELLERATE.GC.PROVIDER.TRANSFORMATION] Could not transform the data
com.thortech.xl.gc.exception.ProviderException: GCPROV.ADAPTER_INPUTSTR_MISSING
at com.thortech.xl.gc.util.TransformationEngine.doTransformation(Unknown Source)
at com.thortech.xl.gc.util.TransformationEngine.transform(Unknown Source)
at com.thortech.xl.gc.runtime.GCAdapterLibrary.executeFunctionality(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.thortech.xl.adapterGlue.ScheduleItemEvents.adpDBAT_PROVISIONING1_GTC.GENERICADAPTER(adpDBAT_PROVISIONING1_GTC.java:125)
at com.thortech.xl.adapterGlue.ScheduleItemEvents.adpDBAT_PROVISIONING1_GTC.implementation(adpDBAT_PROVISIONING1_GTC.java:70)
at com.thortech.xl.client.events.tcBaseEvent.run(Unknown Source)
at com.thortech.xl.dataobj.tcDataObj.runEvent(Unknown Source)
at com.thortech.xl.dataobj.tcScheduleItem.runMilestoneEvent(Unknown Source)
at com.thortech.xl.dataobj.tcScheduleItem.eventPostInsert(Unknown Source)
at com.thortech.xl.dataobj.tcDataObj.insert(Unknown Source)
at com.thortech.xl.dataobj.tcDataObj.save(Unknown Source)
at com.thortech.xl.dataobj.tcORC.insertNonConditionalMilestones(Unknown Source)
at com.thortech.xl.dataobj.tcORC.completeSystemValidationMilestone(Unknown Source)
at com.thortech.xl.dataobj.tcOrderItemInfo.completeCarrierBaseMilestone(Unknown Source)
at com.thortech.xl.dataobj.tcOrderItemInfo.eventPostInsert(Unknown Source)
at com.thortech.xl.dataobj.tcUDProcess.eventPostInsert(Unknown Source)
at com.thortech.xl.dataobj.tcDataObj.insert(Unknown Source)
at com.thortech.xl.dataobj.tcDataObj.save(Unknown Source)
at com.thortech.xl.dataobj.tcTableDataObj.save(Unknown Source)
at com.thortech.xl.ejb.beansimpl.tcFormInstanceOperationsBean.setProcessFormData(Unknown Source)
at com.thortech.xl.ejb.beansimpl.tcFormInstanceOperationsBean.setProcessFormData(Unknown Source)
at com.thortech.xl.ejb.beans.tcFormInstanceOperationsSession.setProcessFormData(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.invocation.Invocation.performCall(Invocation.java:359)
at org.jboss.ejb.StatelessSessionContainer$ContainerInterceptor.invoke(StatelessSessionContainer.java:237)
at org.jboss.resource.connectionmanager.CachedConnectionInterceptor.invoke(CachedConnectionInterceptor.java:158)
at org.jboss.ejb.plugins.StatelessSessionInstanceInterceptor.invoke(StatelessSessionInstanceInterceptor.java:169)
at org.jboss.ejb.plugins.CallValidationInterceptor.invoke(CallValidationInterceptor.java:63)
at org.jboss.ejb.plugins.AbstractTxInterceptor.invokeNext(AbstractTxInterceptor.java:121)
at org.jboss.ejb.plugins.TxInterceptorCMT.runWithTransactions(TxInterceptorCMT.java:350)
at org.jboss.ejb.plugins.TxInterceptorCMT.invoke(TxInterceptorCMT.java:181)
at org.jboss.ejb.plugins.SecurityInterceptor.invoke(SecurityInterceptor.java:168)
at org.jboss.ejb.plugins.LogInterceptor.invoke(LogInterceptor.java:205)
at org.jboss.ejb.plugins.ProxyFactoryFinderInterceptor.invoke(ProxyFactoryFinderInterceptor.java:138)
at org.jboss.ejb.SessionContainer.internalInvoke(SessionContainer.java:648)
at org.jboss.ejb.Container.invoke(Container.java:960)
at sun.reflect.GeneratedMethodAccessor128.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.invocation.local.LocalInvoker$MBeanServerAction.invoke(LocalInvoker.java:169)
at org.jboss.invocation.local.LocalInvoker.invoke(LocalInvoker.java:118)
at org.jboss.invocation.InvokerInterceptor.invokeLocal(InvokerInterceptor.java:209)
at org.jboss.invocation.InvokerInterceptor.invoke(InvokerInterceptor.java:195)
at org.jboss.proxy.TransactionInterceptor.invoke(TransactionInterceptor.java:61)
at org.jboss.proxy.SecurityInterceptor.invoke(SecurityInterceptor.java:70)
at org.jboss.proxy.ejb.StatelessSessionInterceptor.invoke(StatelessSessionInterceptor.java:112)
at org.jboss.proxy.ClientContainer.invoke(ClientContainer.java:100)
at $Proxy769.setProcessFormData(Unknown Source)
at Thor.API.Operations.tcFormInstanceOperationsClient.setProcessFormData(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at Thor.API.Base.SecurityInvocationHandler$1.run(Unknown Source)
at Thor.API.Security.LoginHandler.jbossLoginSession.runAs(Unknown Source)
at Thor.API.Base.SecurityInvocationHandler.invoke(Unknown Source)
at $Proxy813.setProcessFormData(Unknown Source)
at com.thortech.xl.webclient.actions.DirectProvisionUserAction.handleVerifyProcessData(Unknown Source)
at com.thortech.xl.webclient.actions.DirectProvisionUserAction.goNext(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:280)
at com.thortech.xl.webclient.actions.tcLookupDispatchAction.execute(Unknown Source)
at com.thortech.xl.webclient.actions.tcActionBase.execute(Unknown Source)
at com.thortech.xl.webclient.actions.tcAction.execute(Unknown Source)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at com.thortech.xl.webclient.security.SecurityFilter.doFilter(Unknown Source)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:182)
at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.NullPointerException
This Error seems to occur because I was trying to attach certain pre-prop adapters within the default process form that is created while installing the connector. Roaming around the threads here, I came to know that this might be the problem as pre-props don't work fine when applied to the GTC's default form.
To overcome this problem, I've thought of a solution wherein I should create a new Custom Process Form and then apply my pre-props. But for this approach, I'm stuck into the middle. How can I apply a new Custom Form to an existing Provisioning Process ? Is this fesiable ? If yes, where should the changes be made ?
I tried changing the Table Name inside the GTC's provisioning process so that GTC can pick up the my new process form instead of its default process form, but that again gives an error saying :
com.thortech.xl.orb.dataaccess.tcDataAccessException: DB_READ_FAILEDDetail: SQL: select err_key, err_code, err_desc, err_rowver, err_remedy, err_count, err_last_occurance, err_action, err_help_url, err_severity from err where err_code='DOBJ.UPDATE_FAILED'Description: Got a null connectionSQL State: Vendor Code: 0Additional Debug Info:com.thortech.xl.orb.dataaccess.tcDataAccessException
I hope the scenario is clear to you and i'm able to explain upto the mark .. :(
Kindly help me out..
Regards
Nikhil -
Performance Tuning in case of Database Access
Hi,
I am using following code...database access is huge for this code...pls help me out to make database access minimum. I am using 3 internal tables.
select partner1 partner2 into (mtab-busi_part, mtab-BUT051_PART)
from but051.
Select name_first name_last PARTNER_GUID into (mtab-bp_first, mtab-bp_last, MTAB-R_PARTNER_GUID)
From but000 where partner = mtab-busi_part.
*MTAB-OBJECT_ID = ITAB-OBJECT_ID.
append mtab.
endselect.
ENDSELECT.
*ENDLOOP.
loop at mtab.
CONCATENATE mtab-bp_FIRST mtab-bp_LAST INTO mTAB-bp_full
separated BY SPACE.
modify mtab.
endloop.
loop at mtab.
if mtab-bp_full = ' '.
select name_org1 into (mtab-bp_full)
from but000 where partner = mtab-busi_part.
append mtab.
endselect.
endif.
modify mtab.
clear mtab.
endloop.
SELECT OBJECT_ID GUID INTO (NTAB-object_id, Ntab-guid)
FROM CRMD_ORDERADM_H
for all entries in itab
where process_type = '1001' and object_id in o_id.
select single date_1 date_2 from crmv_item_index into (ntab-date_1, ntab-date_2 )
where object_id = ntab-object_id.
endselect.
Select partner_no partner_fct into (Ntab-partner_guid, Ntab-partner_fct)
from bbp_pdview_bup where guid_hi = Ntab-guid .
*and partner_fct <> '00000015'
Select partner name_org1 into (Ntab-partner_no2, Ntab-others)
from but000 where partner_guid = Ntab-partner_guid.
if sy-subrc = 0.
SELECT SINGLE DESCRIPTION FROM CDBC_PARTNER_FT INTO NTAB-DESC
WHERE PARTNER_FCT = NTAB-PARTNER_FCT AND SPRAS = 'EN'.
endif.
SELECT PAFKT ABTNR PAAUTH
FROM BUT051 INTO corresponding fields of nTAB
WHERE PARTNER2 = ntab-partner_no2 .
if sy-subrc = 0.
SELECT single BEZ30 FROM TB913
INTO CORRESPONDING FIELDS OF nTAB
WHERE PAFKT = nTAB-PAFKT AND SPRAS = 'E'.
endif.
if sy-subrc = 0.
SELECT single BEZ20 FROM TB915
INTO CORRESPONDING FIELDS OF nTAB
WHERE PAAUTH = nTAB-PAAUTH AND SPRAS = 'E'.
endif.
*endselect.
if sy-subrc = 0.
SELECT single BEZ20 FROM TB911
INTO (nTAB-BEZ2)
WHERE ABTNR = nTAB-ABTNR AND SPRAS = 'E'.
endif.
endselect.
APPEND NTAB.
*clear ntab.
*ENDSELECT.
ENDSELECT.
*clear ntab.
ENDSELECT.
ENDSELECT.
loop at ntab.
if ntab-others = ' '.
select name_first name_last into (ntab-first_name1, ntab-last_name1)
from but000 where partner = ntab-partner_no2.
endselect.
CONCATENATE ntab-FIRST_NAME1 ntab-LAST_NAME1 INTO nTAB-others
separated BY SPACE.
endif.
modify ntab.
clear ntab.
endloop.
SORT NTAB BY GUID.
SELECT OBJECT_ID GUID INTO (KTAB-object_id, Ktab-guid)
FROM CRMD_ORDERADM_H
for all entries in itab
where process_type = '1001' and object_id in o_id.
Select partner_no into (Ktab-partner_no1)
From crmd_order_index where header = Ktab-guid and pft_8 = 'X' and object_type = 'BUS2000126'.
*endselect.
Select name_first name_last into (Ktab-first_name, Ktab-last_name)
From but000 where partner = Ktab-partner_no1.
*endselect.
APPEND KTAB.
ENDSELECT.
ENDSELECT.
ENDSELECT.
loop at Ktab.
CONCATENATE Ktab-FIRST_NAME Ktab-LAST_NAME INTO KTAB-RESP_EMPLOYEE
separated BY SPACE.
MODIFY KTAB.
clear Ktab.
endloop.
loop at Ktab.
if Ktab-RESP_EMPLOYEE = ' '.
select name_ORG1 into (Ktab-RESP_EMPLOYEE)
from but000 where partner = Ktab-partner_no1.
endselect.
endif.
modify Ktab.
clear Ktab.
endloop.
SELECT OBJECT_ID GUID INTO (itab-object_id, itab-guid)
FROM CRMD_ORDERADM_H
where process_type = '1001' and object_id in o_id.
append itab.
endselect.
LOOP AT iTAB.
LOOP AT NTAB .
IF NTAB-object_id = iTAB-object_id .
itab-date_1 = ntab-date_1.
ITAB-DESC = NTAB-DESC.
itab-partner_no2 = NTab-partner_no2.
itab-partner_fct = ntab-partner_fct.
itab-bez30 = ntab-bez30.
itab-bez20 = ntab-bez20.
itab-bez2 = ntab-bez2.
itab-others = ntab-others.
INSERT lines of nTAB INTO ITAB.
modify itab.
CLEAR ITAB.
delete itab where object_id = ' ' and partner_no2 = ' '.
ENDIF.
endloop.
endloop.
sort itab by OBJECT_ID descending PARTNER_NO2 .
delete adjacent duplicates from itab comparing partner_no2 object_id.
sort itab by OBJECT_ID descending PARTNER_NO2 .
loop at iTab where partner_fct = '00000015'.
LOOP AT mTAB WHERE BUT051_PART = iTAB-partner_no2 .
itab-busi_part = mtab-busi_part.
itab-bp_full = mtab-bp_full.
ITAB-R_PARTNER_GUID = MTAB-R_PARTNER_GUID.
INSERT LINES OF mTAB INTO iTAB.
modify itab transporting busi_part bp_full r_partner_guid.
endloop.
endloop.
sort itab by busi_part descending partner_no2.
delete itab where object_id = ' '.
loop at ITab.
LOOP AT KTAB.
IF KTAB-GUID = ITAB-GUID.
move Ktab-partner_no1 to itab-partner_no1.
move Ktab-R_partner_GUID to itab-R_partner_GUID.
move Ktab-RESP_EMPLOYEE to itab-RESP_EMPLOYEE.
modify itab.
ENDIF.
endloop.
endloop.Hi
i will give you some tips to reduce the daya base load please apply that
<b>Tips and Tricks</b>
Optimizing the load of the database
Using table buffering
Using buffered tables improves the performance considerably. Note that in some cases a statement can not be used with a buffered table, so when using these statements the buffer will be bypassed. These statements are:
Select DISTINCT
ORDER BY / GROUP BY / HAVING clause
Any WHERE clause that contains a sub query or IS NULL expression
JOIN s
A SELECT... FOR UPDATE
If you wan t to explicitly bypass the buffer, use the BYPASS BUFFER addition to the SELECT clause.
Optimizing the load of the database
2. Use the ABAP SORT Clause Instead of ORDER BY
The ORDER BY clause is executed on the database server while the ABAP SORT statement is executed on the application server. The database server will usually be the bottleneck, so sometimes it is better to move the sort from the database server to the application server.
If you are not sorting by the primary key ( E.g. using the ORDER BY PRIMARY key statement) but are sorting by another key, it could be better to use the ABAP SORT statement to sort the data in an internal table. Note however that for very large result sets it might not be a feasible solution and you would want to let the database server sort it.
Optimizing the load of the database
3. Avoid the SELECT DISTINCT Statement
As with the ORDER BY clause it could be better to avoid using SELECT DISTINCT, if some of the fields are not part of an index. Instead use ABAP SORT + DELETE ADJACENT DUPLICATES on an internal table, to delete duplicate rows.
Additional Info
Use of CONTEXT can highly optimize the code.
Context can be created using Context Builder (SE33)
Context advantages: - no double fetch by DEMAND: 1. fetch, 2. get from buffer - more performance (best SELECT-statement) - better survey of code
Use of PARALLEL CURSOR increases the Performance to a great extent.
INDEXES help to speed up selection from the database. The primary index is always created automatically in the SAP System. It consists of the primary key fields of the database table. If you cannot use the primary index to determine a selection result (for example, WHERE condition may not contain any primary index fields), you can create a secondary index.
Optimal number of indexes for a table You should not create more than five secondary indexes for any one table because:
Whenever you change table fields that occur in the index, the index itself is also updated.
The amount of data increases.
The optimizer has too many chances to make mistakes by using the 'wrong' index.
If you are using more than one index for a database table, ensure that they do not overlap.
reward if useful -
Database Access NullPointer Exception in Tomcat
Hi
I have got a problem with database access in my servlet i have folowed all steps of installing and configuring tomcat and i have a DNS that i use to connect to my access database but i get a NullPointerException when i try to create a statement.
please helpPlease show the code.
-
How to handle and manage a multi Database access in runtime with LCDS?
Hello there
I got several customer working with the same application and I wonder how, with LCDS, to manage in a runtime a multi dataBase access; without creating a configuration "mxl" file in
the folder catalina for each database.
Indeed, each customer have their own dataBase, and so far, I did not find out how to avoid creating a config xml file in catalina for every single database; which force me to create as well for each customer a folder application, since the name of the config file in catalina require a folder application to be ran under tomcat....
Thus, my question is :
Is there anyway to create only one configuration mxl file in catalina (in the server side) and then from the client side (application) let the user select its environment (meaning its database) to run the application.... this technic can be also used for multi database environment such as : Dev / Test / Prod environment (or database) where the same application can access to.
Please if any one have an idea or already delt with; just let me know, because I'm entering in a bootle neck and the situation is getting serioulsy critical....
RegardsHello Ulrich,
with compact and repair I mean the MSAccess function "Compact and Repair".
Please follow the link below for more details:
http://office.microsoft.com/en-us/access-help/compact-and-repair-an-access-file-HP005187449.aspx
Normally you can execute this function directly in Access or with the Windows ODBC Data Sources Administrator => "Control Panel" => "Administrative Tools" => "Data Sources (ODBC)"...
I want to execute this function via cvi code and not by hand ;-).
Thank you for your support.
Frank -
How to handle and Manage Multi DataBase access with LCDS in runtime ?
Hello there
I got several customer working with the same application and I wonder how, with LCDS, to manage in a runtime a multi dataBase access; without creating a configuration "mxl" file in
the folder catalina for each database.
Indeed, each customer have their own dataBase, and so far, I did not find out how to avoid creating a config xml file in catalina for every single database; which force me to create as well for each customer a folder application, since the name of the config file in catalina require a folder application to be ran under tomcat....
Thus, my question is :
Is there anyway to create only one configuration mxl file in catalina (in the server side) and then from the client side (application) let the user select its environment (meaning its database) to run the application.... this technic can be also used for multi database environment such as : Dev / Test / Prod environment (or database) where the same application can access to.
Please if any one have an idea or already delt with; just let me know, because I'm entering in a bootle neck and the situation is getting serioulsy critical....
RegardsHello Ulrich,
with compact and repair I mean the MSAccess function "Compact and Repair".
Please follow the link below for more details:
http://office.microsoft.com/en-us/access-help/compact-and-repair-an-access-file-HP005187449.aspx
Normally you can execute this function directly in Access or with the Windows ODBC Data Sources Administrator => "Control Panel" => "Administrative Tools" => "Data Sources (ODBC)"...
I want to execute this function via cvi code and not by hand ;-).
Thank you for your support.
Frank -
am sumanjali.i did a certification programme in database.i know my mc id and i don't know my access code.i want to download my certificate.please help me.
my mc id:10465528.
mail id:<redacted>
candidate id:8753634
site id:90043984
registration:<redacted>You'll need to contact the issuing body for your certification
I'm moving the thread to a forum where someone may be able to point you in the right direction.
Noel Paton | Nil Carborundum Illegitemi
CrashFixPC |
The Three-toed Sloth
No - I do not work for Microsoft, or any of its contractors. -
Why database related code not wriiten in jsp's
hi all
what all resons are there for which database related code
is not written in jsp's
one thing that i know is
it's not a j2ee architecture to do so
so is it the thing that doing so hits the performance issue
thanxMe, I'm still trying to get my head around Java 1.5, J2EE, Tomcat, JBoss, and Oracle RAC (both programming and DBAing)... My head hurts... Badly...
Back to the topic, though... I also agree with the previous posters...
I agree there are exceptions to the "no JDBC in JSP rule of thumb"- I have a JSP-based generic table browser as a tool for emergency maintenance from a (presumably) hostile network, it provides read-only access and automatic password rotation. The flexibility of having it in the JSP has saved my bacon in a crisis; when travelling, I had to talk a non-programmer through applying a code fix (damn developers, using reserved words as column name...)( I had the source on my laptop...). To get a class file fixed, I would have had to get a programmer on the phone, and get the server to reload the class which in our environment at the time required an application restart... The project I work on is about 70 man-years of work, mostly Java, and we have maybe 6 or 8 JSPs that access the DB directly...
Most of the time though, good design says that you access a particular "type" of data (table or group of tables) in the same "chunk" of code, jsp or class file. It's a lot harder to share a jsp among different invokers than it is a class file. It's also better to isolate presentation from data access.
Imagine that you have a "USER" table, with first name, last name, username, and password. You program a "login" jsp, a user "edit" jsp and an administrator "edit" jsp. Then a security audit declares that saving an unexcrypted password in the database is insecure; you now have to change evey place that can access the password. If the user object was accessed through a single Java class file, then there would be only one place to fix. Of course, it's possible to use jsp includes to simulate class files, but that's just about as much work as creating the class file to begin with, with more problems.
Another big advantage of keeping your data access out of JSPs is that you can write unit tests much more easily for the Java classes, using something like JUnit. You can have a set of tests for all your persisted data, which can be run anytime your data model changes. This makes it a lot harder for "side effect" bugs to creep into your code. -
Performance improving in database access
in se30 how shd i c the table acess to in the analysis.
for a kna1 table i shd c the no of accesses.
in 4.6c
goto->objecthitlist->database table is not active ...
is there any other way ..
how shd i confirm that performance is incresed after modifying a code.the SE30 can not help you much with that problem (also the database display which appears ponyl if ou use 'no aggregation' )
For details on database accesses you need to run the SQL Trace, the SQL Trace is in any system since a very long time.
See my weblog for details:
https://www.sdn.sap.com/irj/sdn/weblogs?blog=/cs/junior/search/wlg?id_user=46921
Siegfried -
Hi all. I am trying to write a database access program that is accessible by username and password.I keep getting the following error:
' syntax error( missing operator) in query'
is in this line of code
"SELECT 'selection choices' FROM 'table name' + "WHERE USERNAME LIKE username && WHERE PASSWORD LIKE password)
obviously I don't know what I'm doing. What am I doing wrong? ThanksHard to say since I am not sure what you want to do.
Is "selection choices" a field name? Then a SQL query (which is not the same as java code) would look like this...
SELECT "selection choices" FROM "table name"
WHERE USERNAME LIKE 'username' and WHERE PASSWORD LIKE 'password'
Usually the above would likely look something like this
SELECT "selection choices" FROM "table name"
WHERE USERNAME = 'username' and WHERE PASSWORD = 'password'
Because you would never match on user/password using an approximation.
Doing this is java code would look something like this.
String user = ...
String pwd = ...
StringBuffer s = new StringBuffer();
s.append("SELECT \"selection choices\" FROM \"table name\"");
s.append("WHERE USERNAME = '");
s.append(user);
s.append("' and WHERE PASSWORD = '");
s.append(password);
s.append("'");
String sql = new String(s);
// VERY IMPORTANT STEP. This is how you make sure
// that your java code is producing the correct SQL'
System.out.println("SQL=" + sql);
// Now do the java.sql.* stuff. Note that the \" in the above is rather important but only for your example. If you were using normal field and table names (basically with not spaces) then those would not be needed. -
Regarding database access performance
Hi,
I am pasting the code which i have used to access the database, i m displaying the report in alv format....when i checked it in se30 the results for database access are quite high...how can i optimize the performance.......
SELECT KUNNR
NAME1
INTO TABLE IT_KNA1
FROM KNA1
WHERE KUNNR IN S_KUNNR.
SELECT VBELN
KNUMV
KUNNR
INTO TABLE IT_VBAK
FROM VBAK
FOR ALL ENTRIES IN IT_KNVV
WHERE SPART = IT_KNVV-SPART
AND KUNNR = IT_KNVV-KUNNR.
IF SY-DBCNT = 0.
MESSAGE E001(Z_MESG).
ENDIF.
SELECT KNUMV
KSCHL
KAWRT
INTO TABLE IT_KONV
FROM KONV
FOR ALL ENTRIES IN IT_VBAK
WHERE KNUMV = IT_VBAK-KNUMV.
SELECT VBELN
MATNR
ARKTX
WERKS
NETPR
INTO TABLE IT_VBAP
FROM VBAP
FOR ALL ENTRIES IN IT_VBAK
WHERE WERKS IN S_WERKS
AND MATNR IN S_MATNR
AND VBELN = IT_VBAK-VBELN.
IF SY-DBCNT = 0.
MESSAGE I002(Z_MESG) with s_werks s_matnr.
ENDIF.
SELECT VBELN
FKIMG
NETWR
AUBEL
PRCTR
INTO TABLE IT_VBRP
FROM VBRP
FOR ALL ENTRIES IN IT_VBAP
WHERE AUBEL = IT_VBAP-VBELN.
SELECT VBELN
VGBEL
INTO TABLE IT_LIPS
FROM LIPS
FOR ALL ENTRIES IN IT_VBAP
WHERE VGBEL = IT_VBAP-VBELN.
SELECT DMBTR
XBLNR
INTO TABLE IT_BSIS
FROM BSIS
FOR ALL ENTRIES IN IT_LIPS
WHERE ( HKONT = '0004111013' OR HKONT = '0004111008' OR HKONT = '0004111009' )
AND BUDAT IN S_BUDAT
AND XBLNR = IT_LIPS-VBELN.
IF SY-DBCNT = 0.
MESSAGE I003(Z_MESG) with S_BUDAT.
ENDIF.1. Replace your FOR ALL ENTRIES by RANGES
2. If you would like to use FOR ALL ENTRIES, try to prepare the internal table with only one entry by key (ex the select on KONV, KNUMV is not the key of IT_VBAK, so you will access several times the same key in the database).
I think your reponse time problem is due to the FOR ALL ENTRIES. If you make an ST05 you will show that this command make several access instead of a simple RANGES.
Sometimes it's better to access all the table than select requiered entry (for ex. KNA1).
Fred -
Hi All,
I am having major difficulties with my web application on Sun Web Server 6.1.
After a few days of moderate use (ca. 60 database accesses an hour), my web
server locks up and gives time out errors when requests are made.
After discussing this with fellow programmers, I thought my problem
stems from the database access I use. I wasn't using database connection
pooling, so I thought that might be the answer.
Using the Web server's JDBC Connection Pooling, I set up pooling to work with my application.
Everything seemed to work fine, but after a few days of use, the web server once again locked
up.
Below, please find the class I use to query databases. Do you have suggestions as to how to stream this class or suggestions as to where errors might lurk? Can you see any potential issues with the code I have written?
This class is accessed in the following way: From another class, this call is made:
ConnectAndQuery caq = new ConnectAndQuery();
Vector result = caq.getSelect("Select * from table", theDatabaseIwanttoAccess);
--> now goes to appropriate method in below ConnectAndQuery class
------------------------- ConnectAndQuery.class ----------------------------------------------------
import java.io.*;
import java.net.*;
import java.util.*;
import java.sql.*;
import javax.sql.*;
import javax.naming.InitialContext;
import com.sun.gscc.backend.PropertiesGrabber;
import com.sun.gscc.backend.Communicator;
* Manages database connections.
* @author me
* @version 1.0, 2003-12-02
public class ConnectAndQuery {
protected String sql = "";
protected String dbName = "";
public Connection conn;
public DataSource source;
public Statement stmt;
PropertiesGrabber pg = new PropertiesGrabber();
Communicator c = new Communicator();
* Setter for the sql variable.
* @param givenSql The sql required to process
public void setSql(java.lang.String givenSql) {
sql = givenSql;
* Sets the dbName needed to commect
* to the correct database.
* @param givenDbName Name of the database - name and connections specified within this class
public void setDbName(java.lang.String givenDbName) {
dbName = givenDbName;
* Check completeness of data.
* If sql or dbName not present it'll return false.
* @return String Checks if data is available
protected String checkDataAvailability(){
String returnValue = "";
if(dbName == ""){
returnValue += "\nNo database selected for query";
if(sql == ""){
returnValue += "\nNo SQL statement for query action";
return returnValue;
* Returns the appropriate connection to the required database.
* @return String connection string
* @exception SQLException
* @exception Exception
protected String getConnection(){
try{
InitialContext initContext = new InitialContext();
// First, if test conditions, switch to appropriate test databases.
if(dbName == "sccweb" && pg.getValue("testConditions") != null && pg.getValue("testConditions").equals("true")){
dbName = "yikes";
if(dbName == "maize" && pg.getValue("testConditions") != null && pg.getValue("testConditions").equals("true")){
dbName = "thefarm";
// Then, get connection from configured pool
source = (DataSource) initContext.lookup("java:comp/env/jdbc/" + dbName);
conn = source.getConnection();
stmt = conn.createStatement();
//System.err.println("Opening: " + conn.toString());
return conn.toString();
}catch (SQLException e){
c.emailThis(pg.getValue("adminEmail"), "SCCWebError", "SCCWeb Error: [ConnectAndQuery.getConnection] SQLException", "dbName tried: " + dbName + "\nSQLException: " + e.toString());
return "ConnectAndQuery, SQL Exception:\n" + e.toString();
}catch (Exception e){
c.emailThis(pg.getValue("adminEmail"), "SCCWebError", "SCCWeb Error: [ConnectAndQuery.getConnection] Exception", "dbName tried: " + dbName + "\nException: " + e.toString());
return "ConnectAndQuery, Some other getConnection Exception:\n" + e.toString();
* Takes care of insert, update and delete requests.
* Must have set both dbName as well as the sql String.
* Will return number of rows affected as String.
* @return String Number of rows affected
* @exception SQLException
* @exception Exception
public String getInsertDelete() {
// If insufficient data, bail out miserably
String complete = checkDataAvailability();
String returnValue = "not set";
if(complete != ""){
return "Complete Error: " + complete;
}else{
int rv = 0;
try{
String success = getConnection(); // get this from another function to get correct db
rv = stmt.executeUpdate(sql);
returnValue = "" + rv;
}catch (Exception e){
c.emailThis(pg.getValue("adminEmail"), "SCCWebError", "SCCWeb Error: [ConnectAndQuery.getInsertDelete] Exception", "getInsertDelete Exception: " + e.toString() + "\nWith: " + sql);
returnValue = "ConnectAndQuery, at getInsertDelete, Some other Exception:\n" + e.toString();
}finally{
try{
stmt.close();
conn.close();
}catch(Exception e){
c.emailThis(pg.getValue("adminEmail"), "SCCWebError", "SCCWeb Error: [ConnectAndQuery.getInsertDelete] Exception", "Close() Exception: " + e.toString());
return returnValue;
* Processes Insert and Delete requests with given SQL and DB Name.
* @param givenSql
* @param givenDbName
* @return String Number of rows affected
public String getInsertDelete(String givenSql, String givenDbName){
sql = givenSql;
dbName = givenDbName;
return getInsertDelete();
* Takes care of Select statements.
* Must have set both dbName as well as the sql String.
* Will return a vector.
* @return Vector of Hashes containing the Results of the query
* @exception SQLException
* @exception Exception
public Vector getSelect(){
// If insufficient data, bail out miserably
String complete = checkDataAvailability();
String returnTest = "not set";
Vector returnValue = new Vector();
String connectionString = "not set";
if(complete != ""){
returnTest = "Complete Error: " + complete;
}else{
try{
connectionString = getConnection();
StringBuffer query = new StringBuffer(sql);
ResultSet result = stmt.executeQuery(query.toString());
ResultSetMetaData rsmd = result.getMetaData();
while(result.next()){
Hashtable hash = new Hashtable();
for(int i = 1; i <= rsmd.getColumnCount(); i++){
//System.err.println("-------------------------------");
//System.err.println("SQL: " + sql);
//System.err.println("Index: " + i);
//System.err.println("Test: " + rsmd.getColumnName(i));
//System.err.println("Result: " + result.getString(i));
if(result.getString(i) != null){
hash.put(rsmd.getColumnName(i),result.getString(i));
}else{
hash.put(rsmd.getColumnName(i),"");
returnValue.addElement(hash);
}catch (Exception e){
c.emailThis(pg.getValue("adminEmail"), "SCCWebError", "SCCWeb Error: [ConnectAndQuery.getSelect] Exception", "getSelect Exception: " + e.toString() + "\nWith: " + sql);
returnTest = "ConnectAndQuery, getSelect, Some other getSelect Exception:\n" + e.toString();
}finally{
try{
stmt.close();
conn.close();
//System.err.println("closing: " + connectionString);
}catch(Exception e){
c.emailThis(pg.getValue("adminEmail"), "SCCWebError", "SCCWeb Error: [ConnectAndQuery.getSelect] Exception", "Close() Exception: " + e.toString());
return returnValue;
* Takes care of Select statements with given SQL.
* Must have set both dbName as well as the sql String.
* Will return a vector.
* @return Vector with Results of the query
* @exception SQLException
* @exception Exception
public Vector getSelect(String givenSql, String givenDbName){
sql = givenSql;
dbName = givenDbName;
return getSelect();
}When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read and prevents accidental markup from array indices like [i].
-
Hi im trying to access my ORACLE database through a jsp program. The page loads up in the browser, no errors or anything like that, but i get no output.
I am running things on localhost with TomCat 3.2.3
Here is the code, any help gratefully appreciated.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Testing Database Access</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE"
VLINK="#551A8B" ALINK="#FF0000">
<CENTER>
<TABLE BORDER=5 BGCOLOR="#EF8429">
<TR><TH CLASS="TITLE">
Testing Database Access</TABLE>
</CENTER>
<P>
<P>
Here Is what Might be in the Database
<P>
<%@ page language="java" %>
<%@ page import="java.util.*" %>
<%@ page import="oracle.jdbc.driver.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%
try
%>
<%
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
String username = "Donnchadh", password = "zcbu5mya";
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@kiwi.isg.computing.dcu.ie:1521:kiwi",username,password);
java.sql.Statement stmt = conn.createStatement();
String query = "SELECT * FROM PERSONALS";
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
int ccount = rs.getMetaData().getColumnCount();
for( int i = 1; i <= ccount; i++ )
System.out.print(rs.getString(i)+"\t");
System.out.println();
%>
<%
rs.close();
stmt.close();
if(conn != null)
try
conn.close();
catch(Exception e)
return;
catch(Exception e)
return;
%>
<P>
</BODY>
</HTML>
I have also tried to access columns directly with this code in the while loop
while(rs.next())
String Title = rs.getString("title");
String FName = rs.getString("fname");
String LName = rs.getString("lname");
String Phone = rs.getString("phone1");
String Phone2 = rs.getString("phone2");
String Addr = rs.getString("addr");
String County = rs.getString("county");
String Country = rs.getString("country");
out.println("<tr><td>" + Title + "</td><td>" + FName + "</td><td>" + LName
+ "</td><td>" + Phone + "</td><td>" + Phone2 + "</td></tr>" + "</td></tr>" + Addr
+ "</td></tr>" + County + "</td></tr>" + Country + "</td></tr>" );i give a servlet access to oracle ,that have test ok!
import java.sql.*;
import javax.servlet.*;
import javax.sql.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class TestServlet1 extends HttpServlet {
private static final String CONTENT_TYPE = "image/jpeg; charset=GBK";
//Initialize global variables
String strRno =null;
ResultSet rs=null;
byte [] buf=null;
InputStream in;
int IntNo;
public void init() throws ServletException {
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
// PrintWriter out = response.getWriter();
// System.out.println("TEst database prepaired ok��");
strRno = request.getParameter( "PictNo" );
IntNo = 0;
if( strRno != null ) {
try { IntNo = Integer.parseInt( strRno ); }
catch( NumberFormatException e ) {
strRno = null;
System.out.println("��������������������"); }
else
System.out.println("��������������������");
if( strRno == null ) {
// response.sendError( HttpServletResponse.SC_NOT_FOUND );
return;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
catch (ClassNotFoundException ex2) {
// out.println("TEst2��");
// System.out.println("TEst2�� ex2��");
String url="jdbc:oracle:thin:@erdos00:1521:erdos";
Connection con = null;
try {
con = DriverManager.getConnection(url, "system", "manager");
catch (SQLException ex1) {
//out.println("TEst�� ex1");
System.out.println("TEst�� ex1��");
// PreparedStatement sql=con.PrepareStatement("select photo from blob_test WHERE rno = IntNo" );
PreparedStatement sql = null;
try {
sql = con.prepareStatement("select photo from blob_test WHERE rno = 14 ");
// sql = con.prepareStatement("select photo from blob_test WHERE rno = " +"+ IntNo +" );
catch (SQLException ex) {
//out.println("TEst�� ex");
System.out.println("TEst�� ex��");
//method prepareStatement(sting) not found in interface java.sql.connection
// sql.setInt( 1, rno );
try {
rs = sql.executeQuery();
catch (SQLException ex3) {
//out.println("TEst�� ex3");
System.out.println("TEst�� ex3");
System.out.println("TEst database operate ok��");
// out.println("TEst database operate ok��");
//��������������������
try {
if (rs.next()) {
buf = rs.getBytes(1);
in = rs.getBinaryStream("photo");
else {
buf = new byte[0];
}catch (Exception e){
//throw e;
response.reset();
//������image/jpeg������������������������
response.setContentType("image/bmp");
// ��bmp��jpeg
byte[] b = new byte[1024*1024];
int len;
while((len=in.read(b)) >0)
response.getOutputStream().write(b,0,len);
OutputStream out1 = response.getOutputStream();
out1.flush();
out1.write(buf);
in.close();
try {
rs.close();
catch (SQLException ex4) {
// out.println("<html>");
// out.println("<img src='http://192.168.0.1/examples/servlet/TestServlet1?PictNo="+IntNo+"'>");
// out.println("</html>");
out.println("<html>");
out.println("<head><title>TestServlet</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
out.println("<p>The servlet has received a GET111111111. This is the reply.</p>");
out.println("</body></html>");
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>TestServlet</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
out.println("<p>The servlet has received a POST. This is the reply.</p>");
out.println("</body></html>");
//Process the HTTP Put request
public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Process the HTTP Delete request
public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Clean up resources
public void destroy() {
hope u can get some thing from that
Maybe you are looking for
-
My son posted an album on Facebook; he took the pictures with a regular camera. I shared the album and it immediately showed up on my All-in-One computer and on my Droid phone on my Facebook timeline. It has never appeared on the iPad, so all my frie
-
SQL strange behavior after 11g upgrade
Hi all, After upgrading from 10.2.0.3 to 11.2.0.1 (64-bit RedHat), one of my SQLs behaves very strangely. These are the facts: - This is upgrade evaluation phase in 'lab' environment - First run (after db restart) returns results very quickly (accept
-
How to find my information. The Adobe service is really bad for that... I think to cancel everything !!!
-
I have a scenario here. I have 10 clusters (2 nodes each cluster) I would like to LiveMigrate only a single VM, which is very specific and not mission critical to test the VM every month. This is to test the LiveMigration works on the cluster. I c
-
using vnc in mac, and if your vnc windows is keep repainting, even that windows is not the current screen, the cpu will still 100%