Unable to set string in prepared statement
Hi all,
I just want to set an string to a prepared stmt.
the setting string is in the format..... the integers with comma saparated....
str="23,55,22"
ps.setString(1,str)
The prepare statement is taking only the first integer... i.e. 23
can any one help me out..........
thanks in advance,
prakhyath
if i am not mistaken.... If I create the Prepared
Statement after receiving the arguments that are to
be provided to it.... the actual purpose.. Of using
a prepared statement is not served at all....Not creating a new Statement each time, is only one of the purposes of PreparedStatement. In this case, since the arguments should be ints (and I hope you are checking that), then it doesn't make much of a difference. But a PreparedStatement is alos used to easily facilitate the proper quoting and escaping of the parameters set, which almost eliminates any chance of an SQL injection attack. There are also a few other convienences associated with a PreparedStatement, but, in this case, you are probabyl right in that there is no advantage of PreparedStatement over Statement (as long as you are checking that the arguments provided are actually ints, otherwise you are opening yourself up to an injection attack).
Similar Messages
-
Weblogic generated finder method not setting parameters in prepared statement
Hi,
I am using weblogic 6.1 sp2 and have a CMP bean with a finder defined as follows:
<query>
<query-method>
<method-name>findByPcPayclass</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>SELECT DISTINCT OBJECT(p) FROM Payments p, PaymentType
t WHERE p.paymentType.pcPayClass = '?1'</ejb-ql>
</query>
The weblogic generated code follwos:
public java.util.Collection ejbFindByPcPayclass(java.lang.String param0) throws
javax.ejb.FinderException
if(__WL_verbose) {
Debug.say("called findByPcPayclass");
java.sql.Connection __WL_con = null;
java.sql.PreparedStatement __WL_stmt = null;
java.sql.ResultSet __WL_rs = null;
__WL_pm.flushModifiedBeans();
try {
__WL_con = __WL_pm.getConnection();
} catch (java.lang.Exception e) {
__WL_pm.releaseResources(__WL_con, __WL_stmt, __WL_rs);
throw new javax.ejb.FinderException("Couldn't get connection: " + EOL +
e.toString() + EOL +
RDBMSUtils.throwable2StackTrace(e));
try {
java.lang.String __WL_query = "SELECT WL0.DEPOSIT_UID, WL0.GLA_ID, WL0.MARKET_CODE,
WL0.ORIGINAL_PAYMENT_ID, WL0.PAYMENT_ACCT_NUMBER, WL0.PAYMENT_ACK, WL0.PAYMENT_AMOUNT,
WL0.PAYMENT_CARD_CHECK_NUM, WL0.PAYMENT_CARE_SITE, WL0.PAYMENT_CUST_NAME, WL0.PAYMENT_DESIGNATOR,
WL0.PAYMENT_EFFECTIVE_DATE, WL0.PAYMENT_ID, WL0.PAYMENT_INV_ID, WL0.PAYMENT_MOBILE_NUMBER,
WL0.PAYMENT_SPLIT, WL0.PC_PAYCLASS, WL0.PT_UID, WL0.TT_UID FROM payment_type
WL2, payment_type WL1, payments WL0 WHERE (WL2.PC_PAYCLASS = '?1') AND WL0.PT_UID
= WL2.PT_UID " + __WL_pm.selectForUpdate();
if(__WL_verbose) {
Debug.say("Finder produced statement string " + __WL_query);
__WL_stmt = __WL_con.prepareStatement(__WL_query);
// preparedStatementParamIndex reset.
__WL_rs = __WL_stmt.executeQuery();
} catch (java.lang.Exception e) {
__WL_pm.releaseResources(__WL_con, __WL_stmt, __WL_rs);
throw new javax.ejb.FinderException(
"Exception in findByPcPayclass while preparing or executing " +
"statement: '" + __WL_stmt + "'" + EOL +
e.toString() + EOL +
RDBMSUtils.throwable2StackTrace(e));
The parameter is never set in the prepared statement before it executes. This
causes the finder to return an empty result set. Is this a bug or is there some
configuration that I missed. I am using ant 1.5 to do the ejbc. the ant target
follows:
<target name="ccas.ejbc" depends="ccas.compile, ccas.stage, dd.combine">
<ejbjar srcdir="${buildClasses}/"
descriptordir="${buildOutput}/ear_dd"
basejarname="CCAS"
flatdestdir="true"
dependency="full">
<support dir="${buildClasses}">
<include name="CCAS/**/*.class"/>
</support>
<weblogic destdir="${ear.stage.dir}"
rebuild="false"
keepgenerated="true"
jvmdebuglevel="16">
<classpath refid="classpath"/>
<wlclasspath refid="classpath"/>
</weblogic>
<include name="ejb-jar.xml"/>
<exclude name="**/*-weblogic*.xml"/>
</ejbjar>
</target>replace '?1' with ?1
"Eugene Stephens" <[email protected]> wrote in message
news:[email protected]...
>
Hi,
I am using weblogic 6.1 sp2 and have a CMP bean with a finder defined asfollows:
<query>
<query-method>
<method-name>findByPcPayclass</method-name>
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</query-method>
<ejb-ql>SELECT DISTINCT OBJECT(p) FROM Payments p,PaymentType
t WHERE p.paymentType.pcPayClass = '?1'</ejb-ql>
</query>
The weblogic generated code follwos:
public java.util.Collection ejbFindByPcPayclass(java.lang.String param0)throws
javax.ejb.FinderException
if(__WL_verbose) {
Debug.say("called findByPcPayclass");
java.sql.Connection __WL_con = null;
java.sql.PreparedStatement __WL_stmt = null;
java.sql.ResultSet __WL_rs = null;
__WL_pm.flushModifiedBeans();
try {
__WL_con = __WL_pm.getConnection();
} catch (java.lang.Exception e) {
__WL_pm.releaseResources(__WL_con, __WL_stmt, __WL_rs);
throw new javax.ejb.FinderException("Couldn't get connection: " +EOL +
e.toString() + EOL +
RDBMSUtils.throwable2StackTrace(e));
try {
java.lang.String __WL_query = "SELECT WL0.DEPOSIT_UID, WL0.GLA_ID,WL0.MARKET_CODE,
WL0.ORIGINAL_PAYMENT_ID, WL0.PAYMENT_ACCT_NUMBER, WL0.PAYMENT_ACK,WL0.PAYMENT_AMOUNT,
WL0.PAYMENT_CARD_CHECK_NUM, WL0.PAYMENT_CARE_SITE, WL0.PAYMENT_CUST_NAME,WL0.PAYMENT_DESIGNATOR,
WL0.PAYMENT_EFFECTIVE_DATE, WL0.PAYMENT_ID, WL0.PAYMENT_INV_ID,WL0.PAYMENT_MOBILE_NUMBER,
WL0.PAYMENT_SPLIT, WL0.PC_PAYCLASS, WL0.PT_UID, WL0.TT_UID FROMpayment_type
WL2, payment_type WL1, payments WL0 WHERE (WL2.PC_PAYCLASS = '?1') ANDWL0.PT_UID
= WL2.PT_UID " + __WL_pm.selectForUpdate();
if(__WL_verbose) {
Debug.say("Finder produced statement string " + __WL_query);
__WL_stmt = __WL_con.prepareStatement(__WL_query);
// preparedStatementParamIndex reset.
__WL_rs = __WL_stmt.executeQuery();
} catch (java.lang.Exception e) {
__WL_pm.releaseResources(__WL_con, __WL_stmt, __WL_rs);
throw new javax.ejb.FinderException(
"Exception in findByPcPayclass while preparing or executing " +
"statement: '" + __WL_stmt + "'" + EOL +
e.toString() + EOL +
RDBMSUtils.throwable2StackTrace(e));
The parameter is never set in the prepared statement before it executes.This
causes the finder to return an empty result set. Is this a bug or is theresome
configuration that I missed. I am using ant 1.5 to do the ejbc. the anttarget
follows:
<target name="ccas.ejbc" depends="ccas.compile, ccas.stage,dd.combine">
<ejbjar srcdir="${buildClasses}/"
descriptordir="${buildOutput}/ear_dd"
basejarname="CCAS"
flatdestdir="true"
dependency="full">
<support dir="${buildClasses}">
<include name="CCAS/**/*.class"/>
</support>
<weblogic destdir="${ear.stage.dir}"
rebuild="false"
keepgenerated="true"
jvmdebuglevel="16">
<classpath refid="classpath"/>
<wlclasspath refid="classpath"/>
</weblogic>
<include name="ejb-jar.xml"/>
<exclude name="**/*-weblogic*.xml"/>
</ejbjar>
</target> -
Set char in Prepared Statement
Hi,
Can any one let me know how to set Character value in Prepared Statement. I have my table in which the column is of Char type. Now in my prepared statment, I am saying
PreparedStament pstmt = con.prepareStatement("select ticker from INSTRUMENT_TICKERXREF where ticker = ? ");
pstmt.setString(1,'F');
I even tried pstmt.setString(1,"F");
It gives me incompatible types. Can any please help me on this asap.
Regards,
..RajHi,
I just tried using setString(), it does not seem to give any problems. But in any case, you could use setObject() too.
I tried both setString() and setObject for an example table structure as below:
create table testchar(col1 CHAR(3));
insert into testchar('one');
from java class:
PreparedStatement pstmt = conn.prepareStatement("select col1 from testchar where col1 = ? ");
//pstmt.setObject(1,"one");
pstmt.setString(1,"one");
Hope that helps.
Savitha.
OTN group@IDC -
Setting date in prepared statement
I am using
preparesStatement.setDate(param1,findAuditSearchDTO.getStgAuditGeneral().getAuditBeginDate());
I am wondering setting date this way will slow down the query?
should I use preparesStatement.setString where I can call to_date function or the above code will work fine and not make any difference in performance ?user11138293 wrote:
I am using
preparesStatement.setDate(param1,findAuditSearchDTO.getStgAuditGeneral().getAuditBeginDate());
I am wondering setting date this way will slow down the query? No. And even if it did, it would still be the right way to do it. The main point of using PreparedStatement is so that you can use the correct types in your Java code and don't have to worry about formatting and such.
As far as performance is concerned, any difference introduced by type conversion will be minuscule compared to roundtrip I/O between you and the DB and any disk I/O the DB needs to do. And of course, if it's a DATE column on the DB (which it had better be, if it's representing a date), then the DB would just have to convert the string to a date anyway.
Focus on good design, and on using data structures, algorithms, classes, and methods, that are appropriate to what you're trying to do and that lead to easy-to-understand code. -
ArrayIndexOutOfBoundsException when setting a date in a prepared statement
Hi,
was wondering if anyone could help. I have a prepared statement, with two "variables" in it. I need to set the first of these to a string (using setString(1, "string)
and the second to a date, using setDate(2, SQLDate)
My SQL date is a valid date ass I've run a debugger and checked, but everytime setDate is called an Array Out Of Bound Exception is thrown. Can anyone shed any light on this as I'm rather confused as to why this is happening!
Thanks in advanceI havent got a small runnable example to hand, but taking an excert from my code I have:
for (int i = 0; i < this.columnNames.size();i++)
singleDateEventFlagSingleArea.setString(1, newAreaName);
singleDateEventFlagSingleArea.setDate(2, Date.valueOf((String) this.columnNames.get(i)));
eventFlagsResult = singleDateEventFlagSingleArea.executeQuery()
}newAreaName is a argument passed to the method. columnNames is a vector of dates/strings, which I parse back into a date to pass to the setDate method
Where the value of the date in the statement is changed to a preset value each iteration.
The exception stack I'm getting is:
exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1
at oracle.jdbc.dbaccess.DBDataSetImpl._getDBItem(DBDataSetImpl.java:378)
at oracle.jdbc.dbaccess.DBDataSetImpl._createOrGetDBItem(DBDataSetImpl.java:781)
at oracle.jdbc.dbaccess.DBDataSetImpl.setBytesBindItem(DBDataSetImpl.java:2399)
at oracle.jdbc.driver.OraclePreparedStatement.setItem(OraclePreparedStatement.java:1134)
at oracle.jdbc.driver.OraclePreparedStatement.setDate(OraclePreparedStatement.java:2223)
at treeTableVersion2.TreeTable.updateValuesSingleDateSingleArea(TreeTable.java:393)
at treeTableVersion2.TestWindow.actionPerformed(TestWindow.java:394)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:234)
at java.awt.Component.processMouseEvent(Component.java:5488)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3126)
at java.awt.Component.processEvent(Component.java:5253)
at java.awt.Container.processEvent(Container.java:1966)
at java.awt.Component.dispatchEventImpl(Component.java:3955)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Component.dispatchEvent(Component.java:3803)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
at java.awt.Container.dispatchEventImpl(Container.java:2010)
at java.awt.Window.dispatchEventImpl(Window.java:1774)
at java.awt.Component.dispatchEvent(Component.java:3803)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)Although I think a lot of that is because the process is called by a button press.
The sql statement thats causing the problem is:
select h.areaname,
e.code,
e.descript,
ec.date_raised,
ec.date_progressing,
ec.date_completed
from hareas h, evt_type e, evt_core ec
where h.areaname = ?
and e.evt_type_id = ec.evt_type_id
and (h.nblink = ec.area1_nblink or h.nblink = ec.area2_nblink)
and ec.date_raised = ?
group by h.areaname,
e.code,
e.descript,
ec.date_raised,
ec.date_progressing,
ec.date_completed
order by h.areanameThanks for your help -
Setting date to null in prepared statement
Can anyone tell me how to set a date in Oracle to null using prepared statements.
prepared.setDateHave you tried using the setNull parameter? The following should work for you. (I haven't tested it.)
prepared.setNull(1, Types.DATE); -
String length limitation on setString() in prepared statement
Hi,
Is any body aware of the length of string that can be passed to setString() method of prepared statement. I am getting an error "Data size bigger than max size for this type" if the string length is more than 2000 chars. I am using jdk 1.2.2 for running the application.
Thanks in advance.
Nihar.Please use the following method. It worked for me.
PreparedStatement pstmt = ......;
String str = .....;
pstmt.setObject(index,str,java.sql.Types.LONGVARCHAR);
Ranjan. -
Error Deployer BEA-149231 Unable to set the activation state to true
Hi Friends ,
We are using weblogic 10.3.5.0, one of the deployment module is in failed status.
In the application logs we could see the following error
ERROR Util: Initial Spring Application Context creation failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'datasource' defined in class path resource [spring.xml]: Invocation of init method failed; nested exception is javax.naming.NoPermissionException: User <anonymous> does not have permission on comp.env.cpt to perform lookup operation
in the weblogic server logs we could find the follow error
<24-Jan-2013 08:47:43 o'clock CET> <Warning> <HTTP> <BEA-101162> <User defined listener org.apache.myfaces.webapp.StartupServletContextListener failed: java.lang.ExceptionInInitializerError.java.lang.ExceptionInInitializerError
at com.db.cpt.biz.Utilities.Util.<clinit>(Util.java:114)
at com.db.cpt.web.listener.MyPhaseListener.<clinit>(MyPhaseListener.java:26)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
Truncated. see log file for complete stacktrace
Caused By: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'datasource' defined in class path resource [spring.xml]: Invocati
on of init method failed; nested exception is javax.naming.NoPermissionException: User <anonymous> does not have permission on comp.env.cpt to perform lookup operation.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1170)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:427)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:249)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:155)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:246)
Truncated. see log file for complete stacktrace
Caused By: javax.naming.NoPermissionException: User <anonymous> does not have permission on comp.env.xxx to perform lookup operation.
at weblogic.jndi.internal.ServerNamingNode.checkPermission(ServerNamingNode.java:443)
at weblogic.jndi.internal.ServerNamingNode.checkLookup(ServerNamingNode.java:423)
at weblogic.jndi.internal.ServerNamingNode.lookupHere(ServerNamingNode.java:180)
at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:206)
at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
Truncated. see log file for complete stacktrace
>
<24-Jan-2013 08:47:43 o'clock CET> <Error> <Deployer> <BEA-149231> <Unable to set the activation state to true for the application 'xxx'.
weblogic.application.ModuleException:
at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1510)
at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:482)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:425)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:52)
at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:119)
Truncated. see log file for complete stacktrace
Caused By: javax.naming.NoPermissionException: User <anonymous> does not have permission on comp.env.cpt to perform lookup operation.
at weblogic.jndi.internal.ServerNamingNode.checkPermission(ServerNamingNode.java:443)
at weblogic.jndi.internal.ServerNamingNode.checkLookup(ServerNamingNode.java:423)
at weblogic.jndi.internal.ServerNamingNode.lookupHere(ServerNamingNode.java:180)
at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:206)
at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
Truncated. see log file for complete stacktrace
Can you please advise us how can we resolve this issue which with i am struggling
RajaKumar,
thanks for the update.
we fixed the issue,
for a particular user we didnt add his membership in a group in security realm, we added the user to a particular group, and then restarted weblogic, and deployed the module, and then status of deployment becomes successful.
Raja -
Help with streaming result sets and prepared statements
hi all
I create a callable statement that is capable of streaming.
statement = myConn2.prepareCall("{call graphProc(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}",java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_READ_ONLY);
statementOne.setFetchSize(Integer.MIN_VALUE);
the class that contains the query is instantiated 6 times the first class streams the results beautifully and then when the second
rs = DatabaseConnect.statementOne.executeQuery();
is executed I get the following error
java.sql.SQLException: Can not use streaming results with multiple result statements
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)
at com.mysql.jdbc.MysqlIO.readAllResults(MysqlIO.java:1370)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1688)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3031)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:943)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1049)
at com.mysql.jdbc.CallableStatement.executeQuery(CallableStatement.java:589)
the 6 instances are not threaded and the result set is closed before the next query executes is there a solution to this problem it would be greatly appreciated
thanks a lot
BrianDatabase resources should have the narrowed scope
possible. I don't think it's a good idea to use a
ResultSet in a UI to generate a graph. Load the data
into an object or data structure inside the method
that's doing the query and close the ResultSet in a
finally block. Use the data structure to generate
the graph.
It's an example of MVC and layering.
Ok that is my bad for not elaborating on the finer points sorry, the results are not directly streamed into the graphs from the result set. and are processed in another object and then plotted from there.
with regards to your statement in the beginning I would like to ask if you think it at least a viable option to create six connections. with that said would you be able to give estimated users using the six connections under full usage.
just a few thoughts that I want to
bounce off you if you don't mind. Closing the
statement would defeat the object of of having a
callable statement How so? I don't agree with that.
%again I apologise I assumed that since callable statements inherit from prepared statements that they would have the pre compiled sql statement functionality of prepared statements,well If you consider in the example I'm about to give maybe you will see my point at least with regards to this.
The statement that I create uses a connection and is created statically at the start of the program, every time I make a call the same statement and thus connection is used, creating a new connection each time takes up time and resources. and as you know every second counts
thanks for your thoughts
Brian. -
How to set the number of rings for the agent phone rings before it get the not prepared state
hi, how to set the number of rings for the agent phone rings? before it get the not prepared state.
thanksThe following assumes that you are using ICM with an IPIVR etc (not using CVP), as the answer is different for CVP
What you are looking for is called "Ring no answer time". It is set in the Agent Desk Setting List tool.
Regards,
Kevin -
Unable to set Oracle driver statement cache size to 300
Hi Friends,
when i am starting thread pool worker using threadpoolworker using threadpoolworker.cmd i am getting the error as follows
The root LoggedException was: Unable to set Oracle driver statement cache size to 300
at com.splwg.shared.common.LoggedException.raised(LoggedException.java:65)
at com.splwg.base.support.sql.OracleFunctionReplacer.setOracleCacheSize(OracleFunctionReplacer.java:232)
at com.splwg.base.support.sql.OracleFunctionReplacer.initializeConnectionForNewSession(OracleFunctionReplacer.java:207)
at com.splwg.base.support.context.FrameworkSession.initialize(FrameworkSession.java:225)
at com.splwg.base.support.context.FrameworkSession.<init>(FrameworkSession.java:194)
at com.splwg.base.support.context.ApplicationContext.createSession(ApplicationContext.java:417)
at com.splwg.base.support.context.ApplicationContext.createThreadBoundSession(ApplicationContext.java:461)
at com.splwg.base.support.context.SessionExecutable.doInReadOnlySession(SessionExecutable.java:96)
at com.splwg.base.support.context.SessionExecutable.doInReadOnlySession(SessionExecutable.java:79)
at com.splwg.base.support.context.ApplicationContext.initialize(ApplicationContext.java:211)
at com.splwg.base.support.context.ContextFactory.buildContext(ContextFactory.java:114)
at com.splwg.base.support.context.ContextFactory.buildContext(ContextFactory.java:90)
at com.splwg.base.support.context.ContextFactory.createDefaultContext(ContextFactory.java:498)
at com.splwg.base.api.batch.StandaloneExecuter.setupContext(StandaloneExecuter.java:258)
at com.splwg.base.api.batch.StandaloneExecuter.run(StandaloneExecuter.java:129)
at com.splwg.base.api.batch.StandaloneExecuter.main(StandaloneExecuter.java:357)
at com.splwg.base.api.batch.AbstractStandaloneRunner.invokeStandaloneExecuter(AbstractStandaloneRunner.java:403)
at com.splwg.base.api.batch.AbstractStandaloneRunner.run(AbstractStandaloneRunner.java:134)
at com.splwg.base.api.batch.ThreadPoolWorker.run(ThreadPoolWorker.java:24)
at com.splwg.base.api.batch.ThreadPoolWorker.main(ThreadPoolWorker.java:17)
can any one tell me the exact error
shyam.Hi Friends,
when i am starting thread pool worker using threadpoolworker using threadpoolworker.cmd i am getting the error as follows
The root LoggedException was: Unable to set Oracle driver statement cache size to 300
at com.splwg.shared.common.LoggedException.raised(LoggedException.java:65)
at com.splwg.base.support.sql.OracleFunctionReplacer.setOracleCacheSize(OracleFunctionReplacer.java:232)
at com.splwg.base.support.sql.OracleFunctionReplacer.initializeConnectionForNewSession(OracleFunctionReplacer.java:207)
at com.splwg.base.support.context.FrameworkSession.initialize(FrameworkSession.java:225)
at com.splwg.base.support.context.FrameworkSession.<init>(FrameworkSession.java:194)
at com.splwg.base.support.context.ApplicationContext.createSession(ApplicationContext.java:417)
at com.splwg.base.support.context.ApplicationContext.createThreadBoundSession(ApplicationContext.java:461)
at com.splwg.base.support.context.SessionExecutable.doInReadOnlySession(SessionExecutable.java:96)
at com.splwg.base.support.context.SessionExecutable.doInReadOnlySession(SessionExecutable.java:79)
at com.splwg.base.support.context.ApplicationContext.initialize(ApplicationContext.java:211)
at com.splwg.base.support.context.ContextFactory.buildContext(ContextFactory.java:114)
at com.splwg.base.support.context.ContextFactory.buildContext(ContextFactory.java:90)
at com.splwg.base.support.context.ContextFactory.createDefaultContext(ContextFactory.java:498)
at com.splwg.base.api.batch.StandaloneExecuter.setupContext(StandaloneExecuter.java:258)
at com.splwg.base.api.batch.StandaloneExecuter.run(StandaloneExecuter.java:129)
at com.splwg.base.api.batch.StandaloneExecuter.main(StandaloneExecuter.java:357)
at com.splwg.base.api.batch.AbstractStandaloneRunner.invokeStandaloneExecuter(AbstractStandaloneRunner.java:403)
at com.splwg.base.api.batch.AbstractStandaloneRunner.run(AbstractStandaloneRunner.java:134)
at com.splwg.base.api.batch.ThreadPoolWorker.run(ThreadPoolWorker.java:24)
at com.splwg.base.api.batch.ThreadPoolWorker.main(ThreadPoolWorker.java:17)
can any one tell me the exact error
shyam. -
How do I handle NULL returns from prepared statement?
Thanks in advance to all those who respond. As a beginner with Java/JSP/JDBC, I need all the help I can get!
Here's the problem...
I'm using a prepared statement in JSP to query a MySQL database.
If there is a value to return, everything works properly.
If the query returns a NULL (empty set) value, I get the following error:
javax.servlet.ServletException: Before start of result set
Here's the code (no negative comments please...I know I'm violating some conventions! I'll restructure it later. Right now I just need help with handling the NULL case):
<%
Driver DriverAppt = (Driver)Class.forName(MM_test_DRIVER).newInstance();
Connection ConnAppt = DriverManager.getConnection(MM_test_STRING,MM_test_USERNAME,MM_test_PASSWORD);PreparedStatement StatementAppt = ConnAppt.prepareStatement("SELECT lastname FROM appts_pid1 WHERE user_id = " + Recordset1__MMColParam + " AND year = " + yy + " AND month = '" + months[mm] + "' AND date = " + dates[dd] + " AND appttime = '16:15:00'");
ResultSet Appt = StatementAppt.executeQuery();
boolean Appt_isEmpty = !Appt.first();
boolean Appt_hasData = !Appt_isEmpty;
Object Appt_data;
int Appt_numRows = 0;
%>
Thanks for the help!!!I think I have a better handle on what's occurring here. To cut to the heart of the problem, I'm going to give a very simple example that illustrates what type of error handling I need.
HERE'S THE EXAMPLE:
Let's say that I have a database of users. There are only two columns in the database: user_id and lastname. There are only 2 users, user_id "1" has lastname "Jones" and user_id "2" has lastname "Smith".
I built a very simple web interface that let's a user enter a number to see if there's a lastname associated with that record. The user has no way of knowing if the user_id exists or not, so they may or may not enter a valid number.
If the user enters a valid user_id (in this case "1" or "2"), then the correct lastname is displayed. If the user enters an invalid user_id (in this case, anything other than "1" or "2") then I get the same "Before start of result set" error that I'm getting in my real application.
So, the question is: WHERE IN THIS CODE WOULD I HANDLE THE RETURN OF AN EMPTY SET?
The goal here is to have the sentence say "The user's lastname is .", basically returning null. If there has to be a value, then have the last sentence say "The user's lastname is unknown."
If you can solve this simple example, you'll have also solved the problem with my main application!!!! :-)
Here's the example code:
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
<%@ include file="Connections/example.jsp" %>
<%
String Recordset1__MMColParam = "1";
if (request.getParameter("user_id") !=null) {Recordset1__MMColParam = (String)request.getParameter("user_id");}
%>
<%
Driver DriverRecordset1 = (Driver)Class.forName(MM_example_DRIVER).newInstance();
Connection ConnRecordset1 = DriverManager.getConnection(MM_example_STRING,MM_example_USERNAME,MM_example_PASSWORD);
PreparedStatement StatementRecordset1 = ConnRecordset1.prepareStatement("SELECT * FROM test_table WHERE user_id = " + Recordset1__MMColParam + "");
ResultSet Recordset1 = StatementRecordset1.executeQuery();
boolean Recordset1_isEmpty = !Recordset1.next();
boolean Recordset1_hasData = !Recordset1_isEmpty;
Object Recordset1_data;
int Recordset1_numRows = 0;
%>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form action="test.jsp" method="get" enctype="application/x-www-form-urlencoded" name="form1" target="_self">
<p> Submit a user id and a lastname will be displayed.</p>
<p>
<input type="text" name="user_id">
<input type="submit" name="" value="Submit">
</p>
</form>
<p>The User's lastname is <%=(((Recordset1_data = Recordset1.getObject("lastname"))==null || Recordset1.wasNull())?"":Recordset1_data)%>.</p>
</body>
</html>
<%
Recordset1.close();
StatementRecordset1.close();
ConnRecordset1.close();
%>
A huge "THANK YOU!!!!" to all those who've helped me here!!! -
hi,
i have used following prepared Statement for the update in database.
Can any one tell me that,How can i use date in following method.
I have 4 field for date as given below:(BOLD shown)
I have used String in that place.
It is not working.
PreparedStatement pstatement = conn.prepareStatement(
"UPDATE sec_mast SET catg_code=?, vou_no=?, vou_date=?, vou_amt=?, due_date1=?, due_date2=?, mat_date=? where sec_no=? ");
pstatement.setInt(1,Integer.parseInt(request.getParameter("catg_code")));
pstatement.setString(2,request.getParameter("vou_no"));
pstatement.setString(3,request.getParameter("vou_date"));
pstatement.setInt(4,Integer.parseInt(request.getParameter("vou_amt")));
pstatement.setString(5,request.getParameter("due_date1"));
pstatement.setString(6,request.getParameter("due_date2"));
pstatement.setString(7,request.getParameter("mat_date"));
pstatement.setInt(8,Integer.parseInt(request.getParameter("sec_no")));
int rowCount = pstatement.executeUpdate();
conn.setAutoCommit(false);
conn.setAutoCommit(true);
plz help methanx for u r reply.
MY whole code is shown as below:
This page is for the updating the values in database..
<html>
<body>
<table>
<tr>
<td>
<%@ page import="javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page language="java" import="java.sql.*" %>
<%
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:pf","scott","ttlscott");
System.out.println("got connection");
%>
<%
String action = request.getParameter("action");
// Check if an update is requested
if (action != null && action.equals("update")) {
conn.setAutoCommit(false);
PreparedStatement pstatement = conn.prepareStatement(
"UPDATE sec_mast SET sec_no=? , catg_code=?, face_val=?, pur_val=?, int_paid=?, int_recd=?, brkr=?, vou_no=?, vou_date=?, vou_amt=?, due_date1=?, due_date2=?, lf_no=?, mat_date=? where tot_val=? ");
pstatement.setInt(1,Integer.parseInt(request.getParameter("sec_no")));
pstatement.setInt(2,Integer.parseInt(request.getParameter("catg_code")));
pstatement.setInt(3,Integer.parseInt(request.getParameter("face_val")));
pstatement.setInt(4,Integer.parseInt(request.getParameter("pur_val")));
pstatement.setInt(5,Integer.parseInt(request.getParameter("int_paid")));
pstatement.setInt(6,Integer.parseInt(request.getParameter("int_recd")));
pstatement.setInt(7,Integer.parseInt(request.getParameter("brkr")));
pstatement.setString(8,request.getParameter("vou_no"));
pstatement.setString(9,request.getParameter("vou_date"));
pstatement.setInt(10,Integer.parseInt(request.getParameter("vou_amt")));
pstatement.setString(11,request.getParameter("due_date1"));
pstatement.setString(12,request.getParameter("due_date2"));
pstatement.setString(13,request.getParameter("lf_no"));
pstatement.setString(14,request.getParameter("mat_date"));
pstatement.setInt(15,Integer.parseInt(request.getParameter("tot_val")));
int rowCount = pstatement.executeUpdate();
conn.setAutoCommit(false);
conn.setAutoCommit(true);
%>
<%
// Create the statement
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery
("SELECT * from sec_mast ");
%>
<%
// Iterate over the ResultSet
while ( rs.next() ) {
%>
<tr>
<form action="security_update.jsp" method="get">
<input type="hidden" value="update" name="action">
<td><input value="<%= rs.getInt("sec_no") %>" name="sec_no"></td>
<td><input value="<%= rs.getInt("catg_code") %>" name="catg_code"></td>
<td><input value="<%= rs.getInt("face_val") %>" name="face_val"></td>
<td><input value="<%= rs.getInt("pur_val") %>" name="pur_val"></td>
<td><input value="<%= rs.getInt("int_paid") %>" name="int_paid"></td>
<td><input value="<%= rs.getInt("int_recd") %>" name="int_recd"></td>
<td><input value="<%= rs.getInt("brkr") %>" name="brkr"></td>
<td><input value="<%= rs.getInt("tot_val") %>" name="tot_val"></td>
<td><input value="<%= rs.getString("vou_no") %>" name="vou_no"></td>
<td><input value="<%= rs.getDate("vou_date") %>" name="vou_date"></td>
<td><input value="<%= rs.getInt("vou_amt") %>" name="vou_amt"></td>
<td><input value="<%= rs.getDate("due_date1") %>" name="due_date1"></td>
<td><input value="<%= rs.getDate("due_date2") %>" name="due_date2"></td>
<td><input value="<%= rs.getString("lf_no") %>" name="lf_no"></td>
<td><input value="<%= rs.getDate("mat_date") %>" name="mat_date"></td>
<td><input type="submit" value="Update"></td>
</form>
</tr>
<%
%>
</table>
<%
// Close the ResultSet
rs.close();
// Close the Statement
statement.close();
// Close the Connection
conn.close();
} catch (SQLException sqle) {
out.println(sqle.getMessage());
} catch (Exception e) {
out.println(e.getMessage());
%>
</td>
</tr>
</body>
</html> -
Prepared statement - setDate(index, sql.Date, Cal) Help!
Hi everyone, I'm creating a form to query an Oracle table. I'm setting up the search criteria which includes a start and end date. (in this example I've just used the start date)
I get all the search parameters into my JSP and I created the following Calendar objects:
// Calendar creation
Calendar startCal = Calendar.getInstance();
startCal.set(start_year, start_month, start_day, start_hour, start_minute);
Calendar endCal = Calendar.getInstance();
endCal.set(end_year, end_month, end_day, end_hour, end_minute);
//define a sql.Date value for start and end date
java.sql.Date startDate = null;
java.sql.Date endDate = null;I then create a string that contains my SQL statement:
String sqlStmt = "select dateValue, value3 from someTable where dateValue >= ? and value2 = ?";In my Prepared Statement I pass in the following information:
ps = c.prepareStatement(sqlStmt);
ps.setDate(1, startDate, startCal);
ps.setString(2, searchValue);My question is the following - I define the hour and minute in my Cal object - will that information get passed into my "startDate" sql.Date object? According to the API it should work (at least that's my understading of it):
http://java.sun.com/j2se/1.4.2/docs/api/java/sql/PreparedStatement.html#setDate(int,%20java.sql.Date,%20java.util.Calendar)
My search does not blow up or report any errors but it never finds a match - even when I put in parameters that I know are a match.
Any feedback is appreciated.I think I got it. my java.sql.Date can't be null.
java.sql.Date startDate = null;
java.sql.Date endDate = null;needs to be:
java.util.Date startCalendarDate = startCal.getTime();
java.util.Date endCalendarDate = endCal.getTime();
java.sql.Date startDate = new java.sql.Date(startCalendarDate.getTime());
java.sql.Date endDate = new java.sql.Date(endCalendarDate.getTime()); -
Printing queries in prepared statement
I have a created a prepared statement. When I execute the query I get an error stating that the SQL isn't correct. I would therefore like to print out the statement so I can see what it looks like. Here is what my code is doing.
Create a query string with question marks.
Hand that string off to the preparedStatement constructor.
Modify that string using setString() One for every question mark.
Send the query off by calling executeQuery()
All I want to do is print out what the statement now looks like after the setStrings() are called.
Thanks,
-KAPThat's not a featured guaranteed by the JDBC specification, and because of the way PreparedStatement really works, it can't be.
You see, PreparedStatement usually does not do string replacement into your SQL; the SQL passed to the database still has the ?s in it and the values are bound later, in the database, to a compiled object that is no longer text.
A few drivers will give you back the SQL statement if you apply toString() on the PreparedStatement, and maybe even given you the current values of the bind variables, but most won't.
In fact, normally when you get have invalid SQL with a PreparedStatement, the SQLException is thrown on the prepareStatement method, before the set methods are called; if they're not, then you're probably trying to do an invalid implicit data type conversion. In other words, at least some of the columns in your database are not of character type, and the database is trying to convert your strings to the other type (using its rules, which may be different from Java's rules and may be different from another database's rules), and failing.
Maybe you are looking for
-
HT4539 how to i transfer my games from one ipod to another without starting all over?
can anyone help? i just got the new iPod touch 5th generation, i need to know how to transfer all of my games from my old ipod touch to my new one without starting all over. i want to transfer my games as they are.
-
IMac Nvidia GeForce 8800 GS Drivers
I am running XP Professional via Boot Camp. I run XP so I can play America's Army since it is a Windows only based game. The problem I am having is when I expand Americas Army full screen it completely locks up my iMac and I have to hold down the pow
-
VideoPlayer complete event firing early
I'm not sure why this is happening, but for some reason the complete event is firing about 5-10 seconds into my minutes long video. Here is the code for the VideoPage that loads the video and listens for the events. Does anything seem off to anyone?
-
How to prepare for the EBS R12 Supply Chain OCE Certification
Hello everybody, I post this thread because I'm going to take the exams to get the certification as Oracle EBS R12 Supply Chain Certified Expert Consultant and I'd like to understand how to best prepare myself. Is there anyone who has already got thi
-
Documents related to SUP complete flow(Device to Server and Vice versa).
Hi, Iam using SUP 2.1 ESD#1 licensed version, Please send some documents related to SUP complete flow(Device to Server and Vice versa. Thanks, B.Ushasri