Doubt in PreparedStatement
i am using two tables(walk and run - two are linked with forein key) . In my application by using one input form , sending data into these two tables. i used the PreparedStatement with sql qurey as follows:
PreparedStatement ps=con.prepareStatement("insert into walk(?,?)","insert into run(?)");
(As per syntax PreparedStatement ps=con.prepareStatement(String sqlstatemnt) --- i just given that as i asumed they didn't mention it is a single statement)
is this possiable to use , if not who may fetch data inot tables....
is there any possiabulty to do this with the reference of forein key ids
i am using two tables(walk and run - two are linked
with forein key) . In my application by using one
input form , sending data into these two tables. i
used the PreparedStatement with sql qurey as
follows:
PreparedStatement
ps=con.prepareStatement("insert into
walk(?,?)","insert into run(?)");That isn't valid.
>
(As per syntax PreparedStatement
ps=con.prepareStatement(String sqlstatemnt) --- i
just given that as i asumed they didn't mention it is
a single statementOne string can contain multiple sql statements depending on your database. The format of that depends on your database.
The example you have above is two strings, not one.
>
is this possiable to use , if not who may fetch
data inot tables....
is there any possiabulty to do this with the
reference of forein key idsI can only guess that you want to retrieve the primary key from the first insertion and use it in the second insertion. Some databases allow that. The syntax depends on your database. You can use the gui tool that comes with your database along with the documentation for your database to determine how to do that.
Similar Messages
-
PreparedStatement in two servlets
Hello,
I've got a doubt concerning PreparedStatement with JDBC.
If I have the same statement in two different servlets, is my SQL compiled just once in the DBMS ?
So, if I create a new Instance of PreparedStatement that was previously created in another servlet the statement is not created again.
Is it true?
Thanks.
C.The performance impact of PreparedStatement varies widely from DBMS to DBMS (and driver implementation to driver implementation).
At one end, some systems merely implement PreparedStatement on top of Statement; the SQL is treated identically in the database no matter which statement type you use.
At the other end are DBMS's such as Oracle, that work really hard to optimize PreparedStatement and have several internal layers.
In Oracle, the compilation step is called a "parse", and there are 3 possibilities when executing a SQL statement using a PreparedStatement:
no parse
soft parse
hard parse
A hard or soft parse will occur when the execution connection.PrepareStatement is called. The ideal situation for each SQL statement is "parse once execute many".
In a hard parse, Oracle looks at the SQL, computes a hashcode from the SQL text and looks for an appropriate execution plan in its caches. A cache miss occurs, Oracle prepares the execution plan, saves it in cache keyed by the hashcode, and binds the execution plan to the PreparedStatement (effectively speaking, at least, I'm not sure how the implementation achieves that). It's then ready for parameter binding and execute().
In a soft parse, Oracle looks at the SQL, computes a hashcode from the SQL text and looks for an appropriate execution plan in its caches. A cache hit occurs, Oracle finds an existing execution plan and binds it to the PreparedStatement. Again, we're now ready for binding and execute(). In a parse, the vast bulk of the work and locking occurs in preparing an execution plan, so a soft parse is hugely better than a hard parse.
Parse is avoided totally when new parameters are bound to an existing PreparedStatement and it's then executed. No parse is much better than a soft parse.
You only get a soft parse in Oracle when the SQL matches EXACTLY; case, punctuation, and white space all matter. Also, retention in the cache depends on the memory available to Oracle, and the load on the system, in terms of number of different SQL statements being used. This is why it's so important to use parameter binding; "SELECT a FROM b WHERE c = 1;" is not an exact match for "SELECT a FROM b WHERE c = 2"; using ""SELECT a FROM b WHERE c = ?" allows the cache hit to occur.
So coming back to the way you phrased your question: it would be better to use the same PreparedStatement object in both servlets, but because they're tied to a connection, that can be hard to achieve unless you've got a sophisticated database layer between you and the actual database (some of the better connection poolers also do statement caching if configured to do so). A good second best can be creating and using a new instance of PreparedStatement with IDENTICAL sql.
Hope this clarifies... -
According to msdn , When dealing with Unicode string constants in SQL Server 2005, you must precede all Unicode strings with a capital letter N. The N prefix stands for National Language in the SQL-92 standard, and must be uppercase. If the N prefix is not used, SQL Server uses the non-Unicode code page of the current database before it uses the string. The following example shows how to use the N prefix in code:
UPDATE TableName SET ColumnName = N'Arabic Text' WHERE id = 1000 INSERT INTO TableName (ColumnName) values(N'Arabic Text')My doubt is, this works fine when we are hardcoding the string, but how i can prefix my string variable with N?
My sample code looks like this:
sql = "insert into static_String1 values (?)";
PreparedStatement statement=connection.prepareStatement(sql);
statement.setString(1,statString); //statString is my string variable
statement.executeUpdate();
statement.close();agreed to each and every point of yours... May be my inability to find the error in the original string drove me to look for alternate solutions.
This is how I am getting my string variable
String fileString = files.toString();
InputStream f = new FileInputStream(fileString);
byte[] b = new byte[fileString.length()];
while(!(f.read(b)== -1))
String str = new String(b);
toProcess = toProcess + str;
b = new byte[fileString.length()];
}I cant understand what might be wrong in this.
I tried using BufferedReader as wellString fileString = files[i].toString();
inputStream = new BufferedReader (new FileReader(fileString));
String str ;
while ((str = inputStream.readLine())!=null){
statString=statString+str;
}Still, no use. -
Why can't I select or update the Record using the PreparedStatement?
the DB is oracle9i,here is the test table
test
id number;
name char(10);
intro char(10);
I have insert a record in the table.
Now I will select or update the record by using the PreparedStatement here is my code:
sqlStr = "update test set intro = ? where name =?";
PreparedStatement stmt = conn.prepareStatement(sqlStr);
stmt.setString(1,"my name is irixwang");
stmt.setString(2,"irixwang");
int is = stmt.executeUpdate();
if (is >=1 )
System.out.println("ok");
It will not work ,but where I change the update condiction as followed:
sqlStr = "update test set intro = ? where id =?";
PreparedStatement stmt = conn.prepareStatement(sqlStr);
stmt.setString(1,"my name is irixwang");
stmt.setInt(2,100);
int is = stmt.executeUpdate();
It works well,why?
please help me!thk!!!!I doubt it works "well" in either case since you are inserting a string that is longer than 10 characters into a field that only holds 10 characters. But to your question....
A char data type holds a fixed number of characters - in your case 10.
Because it holds 10 characters it will never hold 9, regardless of what you think is in the field it will always have 10 characters in it. The value you are using for query for name is 9 characters. Since 9 characters, regardless of content, will never be equal to 10 characters there is no way that it will update.
So your choice is to either use a varchar, which holds a variable number of characters, or to always use 10 characters for your query (pad it with spaces.) -
I've developed an MDB that reads a message from a queue, performs database updates
against up to 2 databases, and sends an outgoing JMS message when all is complete.
The MDB uses container-managed transactions to ensure that all DB updates and
JMS messages are committed or rolled back together. I have had a lot of problems
related to transactions failing, becoming "in-doubt" in the database and locking
database resources indefinitely.
My environment is configured as follows:
WebLogic 8.1.2 Server
Oracle 9.2.0.4 database with RAC
XA Connection Pool with WebLogic Type 2 Oracle Driver OR Oracle 9.2.0.4
OCI Driver
I have read the BEA/HP white paper regarding Weblogic 8.1 with Oracle 9i RAC (http://dev2dev.bea.com/products/wlserver81/whitepapers/wls_bea_hp.jsp)
and have tried all of the solutions suggested in that paper. The only solution
that worked consistently without causing the in-doubt transactions was to change
my connection pools to point directly to a single node of the RAC cluster, not
to the shared instance. However, even with this configuration, I have seen these
errors occur when certain database failures occur.
A side-effect of this problem is that the associated WebLogic connection pools
begin to "forget" connections. The pool thinks that all of the connections are
in use (even though I am always calling Statement.close() and Connection.close()),
and the connection pool cannot be reset manually. The only way to clear the connection
pool is to bounce WebLogic.
The only posts I have found related to this error were regarding Oracle 8.1.7
and WebLogic 6.1. Any help would be greatly appreciated.
Exceptions:
<Mar 23, 2004 2:59:36 PM EST> <Error> <EJB> <BEA-010026> <Exception occurred during
commit of transaction Xid=BEA1-0526A28664707F28EDB9(6412513),Status=Rolled back.
[Reason=javax.transaction.xa.XAException
: prepare failed for XAResource 'ProfilingPool' with error XAER_NOTA : The XID
is not valid],numRepliesOwedMe=0,numRepliesOwedOthers=0,seconds since begin=2,seconds
left=60,XAServerResourceInfo[JMS_my
JmsStore]=(ServerResourceInfo[JMS_myJmsStore]=(state=rolledback,assigned=myserver),xar=JMS_myJmsStore),XAServerResourceInfo[ProfilingPool]=(ServerResourceInfo[ProfilingPool]=(state=rolledback,ass
igned=myserver),xar=ProfilingPool),SCInfo[mydomain+myserver]=(state=rolledback),local
properties=({}),OwnerTransactionManager=ServerTM[ServerCoordinatorDescriptor=(CoordinatorURL=myserver+10.41.0.61:7001+m
ydomain+t3+, XAResources={JMS_myJmsStore, JMS_FileStore, ProfilingPool, SearchManagementPool,
AnnouncementsTxPool},NonXAResources={})],CoordinatorURL=myserver+10.41.0.61:7001+mydomain+t3+):
javax.tran
saction.xa.XAException: prepare failed for XAResource 'ProfilingPool' with error
XAER_NOTA : The XID is not valid
at weblogic.jdbc.oci.xa.XA.createException(XA.java:386)
at weblogic.jdbc.oci.xa.XADataSource.internalPrepare(XADataSource.java:905)
at weblogic.jdbc.oci.xa.XADataSource.prepare(XADataSource.java:885)
at weblogic.jdbc.jta.DataSource.prepare(DataSource.java:846)
at weblogic.transaction.internal.XAServerResourceInfo.prepare(XAServerResourceInfo.java:1167)
at weblogic.transaction.internal.XAServerResourceInfo.prepare(XAServerResourceInfo.java:401)
at weblogic.transaction.internal.ServerSCInfo$1.execute(ServerSCInfo.java:253)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
--------------- nested within: ------------------
weblogic.transaction.RollbackException: Could not prepare resource 'ProfilingPool
prepare failed for XAResource 'ProfilingPool' with error XAER_NOTA : The XID is
not valid - with nested exception:
[javax.transaction.xa.XAException: prepare failed for XAResource 'ProfilingPool'
with error XAER_NOTA : The XID is not valid]
at weblogic.transaction.internal.TransactionImpl.throwRollbackException(TransactionImpl.java:1644)
at weblogic.transaction.internal.ServerTransactionImpl.internalCommit(ServerTransactionImpl.java:300)
at weblogic.transaction.internal.ServerTransactionImpl.commit(ServerTransactionImpl.java:221)
at weblogic.ejb20.internal.MDListener.execute(MDListener.java:412)
at weblogic.ejb20.internal.MDListener.transactionalOnMessage(MDListener.java:316)
at weblogic.ejb20.internal.MDListener.onMessage(MDListener.java:281)
at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:2596)
at weblogic.jms.client.JMSSession.execute(JMSSession.java:2516)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
2004-03-23 15:00:45,406 ERROR IS003989 [ExecuteThread: '17' for queue: 'ProfileCompleteListenerBean.ExecuteQueue']
my.package.search.business.ProfiledHoldingDAO.setProfilingStatus(ProfiledHoldingDAO.java:350
) - Failed to update profiling status for holding 10014 [] (-2)
java.sql.SQLException: ORA-02049: timeout: distributed transaction waiting for
lock
at weblogic.db.oci.OciCursor.getCDAException(OciCursor.java:282)
at weblogic.jdbc.oci.PreparedStatement.executeUpdate(PreparedStatement.java:226)
at weblogic.jdbc.oci.xa.PreparedStatement.executeUpdate(PreparedStatement.java:81)
at weblogic.jdbc.wrapper.PreparedStatement.executeUpdate(PreparedStatement.java:94)
at my.package.search.business.ProfiledHoldingDAO.setProfilingStatus(ProfiledHoldingDAO.java:345)
at my.package.search.business.ProfilingManager.disseminateAndAcknowledge(ProfilingManager.java:254)
at my.package.search.business.ProfileCompleteListenerBean.onMessage(ProfileCompleteListenerBean.java:128)
at weblogic.ejb20.internal.MDListener.execute(MDListener.java:382)
at weblogic.ejb20.internal.MDListener.transactionalOnMessage(MDListener.java:316)
at weblogic.ejb20.internal.MDListener.onMessage(MDListener.java:281)
at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:2596)
at weblogic.jms.client.JMSSession.execute(JMSSession.java:2516)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
2004-03-23 15:01:43,093 ERROR IS003989 [ExecuteThread: '18' for queue: 'HoldingStatusListenerBean.ExecuteQueue']
my.package.search.business.ProfiledHoldingDAO.getProfilingStatus(ProfiledHoldingDAO.java:265)
- Failed to retrieve profiling results for holding 10060 [] (-2)
java.sql.SQLException: ORA-01591: lock held by in-doubt distributed transaction
189.47.12
at weblogic.db.oci.OciCursor.getCDAException(OciCursor.java:282)
at weblogic.jdbc.oci.PreparedStatement.executeQuery(PreparedStatement.java:152)
at weblogic.jdbc.oci.xa.PreparedStatement.executeQuery(PreparedStatement.java:48)
at weblogic.jdbc.wrapper.PreparedStatement.executeQuery(PreparedStatement.java:80)
at my.package.search.business.ProfiledHoldingDAO.getProfilingStatus(ProfiledHoldingDAO.java:256)
at my.package.search.business.ProfiledHoldingDAO.storeHoldingMetadata(ProfiledHoldingDAO.java:489)
at my.package.search.business.ProfiledHoldingDAO.storeNewHolding(ProfiledHoldingDAO.java:406)
at my.package.search.business.ProfilingManager.profileHolding(ProfilingManager.java:128)
at my.package.search.business.HoldingStatusListenerBean.onMessage(HoldingStatusListenerBean.java:121)
at weblogic.ejb20.internal.MDListener.execute(MDListener.java:382)
at weblogic.ejb20.internal.MDListener.transactionalOnMessage(MDListener.java:316)
at weblogic.ejb20.internal.MDListener.onMessage(MDListener.java:281)
at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:2596)
at weblogic.jms.client.JMSSession.execute(JMSSession.java:2516)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
Hi. There is a serious bug in the Oracle DBMS (all versions) where in-doubt
transactions have their data locked in the DBMS by page rather than by row,
so it will indefinitely prevent access to all data on the page, including
logically uninvolved data. Oracle understands the problem but currently
says they will never fix it (it would take too much work). They offer the
alternative that you configure your table data to ensure that no more than
one datarow resides on a page.
Joe
Matt Smith wrote:
> I've developed an MDB that reads a message from a queue, performs database updates
> against up to 2 databases, and sends an outgoing JMS message when all is complete.
> The MDB uses container-managed transactions to ensure that all DB updates and
> JMS messages are committed or rolled back together. I have had a lot of problems
> related to transactions failing, becoming "in-doubt" in the database and locking
> database resources indefinitely.
>
> My environment is configured as follows:
> WebLogic 8.1.2 Server
> Oracle 9.2.0.4 database with RAC
> XA Connection Pool with WebLogic Type 2 Oracle Driver OR Oracle 9.2.0.4
> OCI Driver
>
> I have read the BEA/HP white paper regarding Weblogic 8.1 with Oracle 9i RAC (http://dev2dev.bea.com/products/wlserver81/whitepapers/wls_bea_hp.jsp)
> and have tried all of the solutions suggested in that paper. The only solution
> that worked consistently without causing the in-doubt transactions was to change
> my connection pools to point directly to a single node of the RAC cluster, not
> to the shared instance. However, even with this configuration, I have seen these
> errors occur when certain database failures occur.
>
> A side-effect of this problem is that the associated WebLogic connection pools
> begin to "forget" connections. The pool thinks that all of the connections are
> in use (even though I am always calling Statement.close() and Connection.close()),
> and the connection pool cannot be reset manually. The only way to clear the connection
> pool is to bounce WebLogic.
>
> The only posts I have found related to this error were regarding Oracle 8.1.7
> and WebLogic 6.1. Any help would be greatly appreciated.
>
> Exceptions:
> -----------------
> <Mar 23, 2004 2:59:36 PM EST> <Error> <EJB> <BEA-010026> <Exception occurred during
> commit of transaction Xid=BEA1-0526A28664707F28EDB9(6412513),Status=Rolled back.
> [Reason=javax.transaction.xa.XAException
> : prepare failed for XAResource 'ProfilingPool' with error XAER_NOTA : The XID
> is not valid],numRepliesOwedMe=0,numRepliesOwedOthers=0,seconds since begin=2,seconds
> left=60,XAServerResourceInfo[JMS_my
> JmsStore]=(ServerResourceInfo[JMS_myJmsStore]=(state=rolledback,assigned=myserver),xar=JMS_myJmsStore),XAServerResourceInfo[ProfilingPool]=(ServerResourceInfo[ProfilingPool]=(state=rolledback,ass
> igned=myserver),xar=ProfilingPool),SCInfo[mydomain+myserver]=(state=rolledback),local
> properties=({}),OwnerTransactionManager=ServerTM[ServerCoordinatorDescriptor=(CoordinatorURL=myserver+10.41.0.61:7001+m
> ydomain+t3+, XAResources={JMS_myJmsStore, JMS_FileStore, ProfilingPool, SearchManagementPool,
> AnnouncementsTxPool},NonXAResources={})],CoordinatorURL=myserver+10.41.0.61:7001+mydomain+t3+):
> javax.tran
> saction.xa.XAException: prepare failed for XAResource 'ProfilingPool' with error
> XAER_NOTA : The XID is not valid
> at weblogic.jdbc.oci.xa.XA.createException(XA.java:386)
> at weblogic.jdbc.oci.xa.XADataSource.internalPrepare(XADataSource.java:905)
> at weblogic.jdbc.oci.xa.XADataSource.prepare(XADataSource.java:885)
> at weblogic.jdbc.jta.DataSource.prepare(DataSource.java:846)
> at weblogic.transaction.internal.XAServerResourceInfo.prepare(XAServerResourceInfo.java:1167)
> at weblogic.transaction.internal.XAServerResourceInfo.prepare(XAServerResourceInfo.java:401)
> at weblogic.transaction.internal.ServerSCInfo$1.execute(ServerSCInfo.java:253)
> at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
> at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
> --------------- nested within: ------------------
> weblogic.transaction.RollbackException: Could not prepare resource 'ProfilingPool
> prepare failed for XAResource 'ProfilingPool' with error XAER_NOTA : The XID is
> not valid - with nested exception:
> [javax.transaction.xa.XAException: prepare failed for XAResource 'ProfilingPool'
> with error XAER_NOTA : The XID is not valid]
> at weblogic.transaction.internal.TransactionImpl.throwRollbackException(TransactionImpl.java:1644)
> at weblogic.transaction.internal.ServerTransactionImpl.internalCommit(ServerTransactionImpl.java:300)
> at weblogic.transaction.internal.ServerTransactionImpl.commit(ServerTransactionImpl.java:221)
> at weblogic.ejb20.internal.MDListener.execute(MDListener.java:412)
> at weblogic.ejb20.internal.MDListener.transactionalOnMessage(MDListener.java:316)
> at weblogic.ejb20.internal.MDListener.onMessage(MDListener.java:281)
> at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:2596)
> at weblogic.jms.client.JMSSession.execute(JMSSession.java:2516)
> at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
> at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
> ...
> 2004-03-23 15:00:45,406 ERROR IS003989 [ExecuteThread: '17' for queue: 'ProfileCompleteListenerBean.ExecuteQueue']
> my.package.search.business.ProfiledHoldingDAO.setProfilingStatus(ProfiledHoldingDAO.java:350
> ) - Failed to update profiling status for holding 10014 [] (-2)
> java.sql.SQLException: ORA-02049: timeout: distributed transaction waiting for
> lock
> at weblogic.db.oci.OciCursor.getCDAException(OciCursor.java:282)
> at weblogic.jdbc.oci.PreparedStatement.executeUpdate(PreparedStatement.java:226)
> at weblogic.jdbc.oci.xa.PreparedStatement.executeUpdate(PreparedStatement.java:81)
> at weblogic.jdbc.wrapper.PreparedStatement.executeUpdate(PreparedStatement.java:94)
> at my.package.search.business.ProfiledHoldingDAO.setProfilingStatus(ProfiledHoldingDAO.java:345)
> at my.package.search.business.ProfilingManager.disseminateAndAcknowledge(ProfilingManager.java:254)
> at my.package.search.business.ProfileCompleteListenerBean.onMessage(ProfileCompleteListenerBean.java:128)
> at weblogic.ejb20.internal.MDListener.execute(MDListener.java:382)
> at weblogic.ejb20.internal.MDListener.transactionalOnMessage(MDListener.java:316)
> at weblogic.ejb20.internal.MDListener.onMessage(MDListener.java:281)
> at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:2596)
> at weblogic.jms.client.JMSSession.execute(JMSSession.java:2516)
> at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
> at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
> ...
> 2004-03-23 15:01:43,093 ERROR IS003989 [ExecuteThread: '18' for queue: 'HoldingStatusListenerBean.ExecuteQueue']
> my.package.search.business.ProfiledHoldingDAO.getProfilingStatus(ProfiledHoldingDAO.java:265)
> - Failed to retrieve profiling results for holding 10060 [] (-2)
> java.sql.SQLException: ORA-01591: lock held by in-doubt distributed transaction
> 189.47.12
> at weblogic.db.oci.OciCursor.getCDAException(OciCursor.java:282)
> at weblogic.jdbc.oci.PreparedStatement.executeQuery(PreparedStatement.java:152)
> at weblogic.jdbc.oci.xa.PreparedStatement.executeQuery(PreparedStatement.java:48)
> at weblogic.jdbc.wrapper.PreparedStatement.executeQuery(PreparedStatement.java:80)
> at my.package.search.business.ProfiledHoldingDAO.getProfilingStatus(ProfiledHoldingDAO.java:256)
> at my.package.search.business.ProfiledHoldingDAO.storeHoldingMetadata(ProfiledHoldingDAO.java:489)
> at my.package.search.business.ProfiledHoldingDAO.storeNewHolding(ProfiledHoldingDAO.java:406)
> at my.package.search.business.ProfilingManager.profileHolding(ProfilingManager.java:128)
> at my.package.search.business.HoldingStatusListenerBean.onMessage(HoldingStatusListenerBean.java:121)
> at weblogic.ejb20.internal.MDListener.execute(MDListener.java:382)
> at weblogic.ejb20.internal.MDListener.transactionalOnMessage(MDListener.java:316)
> at weblogic.ejb20.internal.MDListener.onMessage(MDListener.java:281)
> at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:2596)
> at weblogic.jms.client.JMSSession.execute(JMSSession.java:2516)
> at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:197)
> at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:170)
>
>
-
CREATE VIEW with PreparedStatement
Hi guys,
I'm trying to run a CREATE VIEW statement, which I have been doing up till now just using a regular Statement, and using the executeUpdate() method. It's been working fine for a while, and now i've hit a bit of a problem.
I can't include a WHERE clause in a Statement, as it doesn't like the single quotations (') and wildcards. After searching this forum, I saw that I should be using a PreparedStatement, and using the setString() method to put in the ' and %'s.
Now when I try to run the PreparedStatement using the executeUpdate() method, I get the "Incorrect syntax near the keyword 'VIEW'" error. Can anyone tell me if i'm using the right method for executing the PreparedStatement, or what i'm doing wrong?
Regards,
Jack SmithSQL statements are often broken up into two classes, DML (data manipulation language) and DDL (data definition language). DML contains the normal CRUD statements, INSERT, SELECT, UPDATE, DELETE and anything else that modifes the data but not the data structure. DDL is the set of statements that manipulates the data structure, things like CREATE, ALTER, DROP.
As a general rule of thumb, you shouldn't do DDL in a PreparedStatement.
PreparedStatements exist primarily to allow late-binding of data-value objects into the internal datastructure within the database that represents a parsed SQL statement's execution plan. It is NOT a mechanism for doing string substitution (though I understand who it can look that way to beginners).
Another way of saying this is that PreparedStatement is based on the distinction between data and code; in a DDL statement, the entire statement is code.
There are a few drivers/databases where this might happen to work, because they aren't really seriously implementing PreparedStatement but merely doing string replacement to fake it. I very much doubt SQL server is going to be one of these. -
PreparedStatement: pure interest
Hi
Latelly I was making some investigations... When writing queries I always use PreparedStatement class to arm ones, because I know it's more secure, and it's an effective protection against SQL injection. Therefore I was wondering how the "final" query looks like in the moment of execution.
The most simple answer maybe would be that the setString() function for ex. for the case:
SELECT * FROM TABLE WHERE USER=?
stmt.setString(1, user)
user = " ' or 1=1 -- " //or something like that, SQL injection is SQL injection =)
would convert its parameter using escape to:
" \' or 1=1 \-- " - or something like that. But it looks too simple to me, so here lies my doubt.
I suppose I'd be happy just taking a look at the soursce code of the PreparedStatement.setString() function for ex., or the final query itself.
I looked for various sourcecodes in the network and didn't find any. Maybe that's a little bit lamish but if it is here somewhere it's pretty hidden from users.Why don't you take a look at this:
http://www.javaworld.com/javaworld/jw-01-2002/jw-0125-overpower.html
Awesome, that's exactly what I needed. Thanks a lot to all. =)
2StuDerby: mmm, right now I'm writing for Oracle mostly and things are not so differenet there from MySQL. I have done many tests, trying things from SQL injection (with/without) proxy to bruteforsing the fields. PreparedSatetment rulez. -
Setting parameter in PreparedStatement results in different stored value
Hi,
first of all: this might be an exotic case!
When setting a parameter value of a PreparedStatement using Types.DECIMAL as sql-parameter-type like this:
stm.setObject(x, new Long(92233720368547758l), Types.DECIMAL);the value in the database is 92233720368547758 but 92233720368547760. When I set the sql-parameter-type to Types.BIGINT:
stm.setObject(x, new Long(92233720368547758l), Types.BIGINT);the value is stored correctly. This just happens on values >9223372036854770.
Can anyone explain why? As I changed the jdbc driver a few times I doubt it's a bug in the driver but more a wanted/special behaviour for this sql-type ;)
Regards,
Stefanoh, just found out after decompiling the jdbc driver :D
If the sql-type is Types.DECIMAL and the value is an instance of Number the driver does this here:
new BigDecimal(((Number) VALUE).doubleValue())When calling Long.double() 92233720368547758 results into 9.223372036854776E16 and therefore we already have a different value. I'll just fix our code then to use Types.BIGINT instead of Types.DECIMAL. -
Doubt handling Clob columns with Java JDBC api
Hi,
we have a doubt handling Clob columns with Java JDBC api.
Reading Oracle 10g official documentation (document b10979.pdf, page 236), we found this note:
============================================
To write LOB data, the application must acquire a write lock on the LOB object. One way to accomplish this is through a SELECT FOR UPDATE. Also, disable auto-commit mode.
============================================
We also found a java sample code about how to handle Lob objects at this URL:
http://www.oracle.com/technology/sample_code/tech/java/sqlj_jdbc/files/advanced/LOBSample/LOBSample.java.html
In our java2 application, we access Clob objects in a quite different
manner: we use normal setString() and getString() methods, as described into paragraph "Shortcuts For Inserting and Retrieving CLOB Data"
(document b10979.pdf, page 244).
Using those methods, we never lock the table row by a SELECT FOR UPDATE statement (as described into the note above). We use simply SELECT, UPDATE and INSERT prepared statement.
In this way we can insert both clob objects and normal timestamp, number and other types with a single insert statement. Idem for update.
To recap, our question is:
Is it mandatory to create a SELECT FOR UPDATE statement when updating clob data? What may be the consequences if we don't use it? It is also correct to insert with a single sql statement both clob and not clob data using the setString() method for the clob types? And more than one lob column in the same record?
bye,
luca acri.And columns of type FLOAT. These also have, for some unknown reason a metadata type of OTHER, and a type string of 'FLOAT'. Yet PreparedStatement.setNull(x, Types.OTHER) doesn't work and setNull(x, Types.DECIMAL) does.
-
Could someone comment on my code please. I'm reusing the PreparedStatement (delete) below for different queries before closing the PreparedStatement (delete is closed in this.close()). The API for Statement.close() states:
Releases this Statement object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. It is generally good practice to release resources as soon as you are finished with them to avoid tying up database resources.
...but what resources would be wasted if the PreparedStatement is reused AND is this opening the app up to innefficency/overhead?
Your reply is appreciated. Code below....
public boolean cascadeDeleteRfxForm() throws SQLException, Exception{
boolean deleteFlag=true;
try{
//create connection
this.createConnection();
//set autocommit to fals - allows batch commit/rollback
con.setAutoCommit(false);
//create prepare statement from string
delete=con.prepareStatement(deleteRfxItemAttr);
delete.setString(1, orgId);
delete.setString(2, rfxName);
delete.setString(3, rfxUniqueId);
delete.setString(4, revNbr);
//execute prepared statement
delete.execute();
//create prepared statment from string
delete=con.prepareStatement(deleteRfxAttr);
delete.setString(1, orgId);
delete.setString(2, rfxName);
delete.setString(3, rfxUniqueId);
delete.setString(4, revNbr);
//execute prepared statement
delete.execute();
//create prepared statment from string
delete=con.prepareStatement(deleteRfxItem);
delete.setString(1, orgId);
delete.setString(2, rfxName);
delete.setString(3, rfxUniqueId);
delete.setString(4, revNbr);
//execute prepared statement
delete.execute();
//delete parent - create prepared statment from string
delete=con.prepareStatement(deleteUniqueRfxHeader);
delete.setString(1, orgId);
delete.setString(2, rfxName);
delete.setString(3, rfxUniqueId);
delete.setString(4, revNbr);
delete.execute();
catch(Exception e){
deleteFlag=false;
con.rollback();
throw e;
finally {
try {
if(deleteFlag==true){
con.commit();
System.out.println("Comited");
con.setAutoCommit(true);
this.close();
catch (Exception ex) {}
return deleteFlag;
}I don't see anything in the posted code that explicitly suggests that a prepared statement is being used more than once.
More than one prepared statement is being created (and not explicitly closed.) They might or might not produce the same database resource depending on the database/driver or not.
And from the performance perspective, if and only if, the same database resource is being used then there might be some small performance increase. Although I doubt that it is measurable/significant as a database round trip is probably required for each. -
hi i have a doubt....
in fbl1n transaction, there are open items and cleared items.
in it the cleared items for certain document types such as invoice etc is not present in the open item table (bsik)
however the cleared items for document types such as general voucher its present in the open items table (bsik)
is this possible as all cleared item entries shld b present in the open item table with an indicator set for cleared or not...
plz exlain!Hi
There are 2 tables(open and Closed Items) in FI for Account Payables and Account Receivables and GL accounts
1.Account payables: BSIK is Open Items and BSAK is Closed items
2.Account Receivables; BSID and BSAD for OPEN and closed items
3/GL accounts : BSIS and BSAS for Open and Closed Items
<b>Reward points for useful Answers</b>
Regards
Anji -
How to print Integrity sql in the preparedstatement?
How to print Integrity sql in the preparedstatement?
Connection conn = null;
String sql = "select * from person where name=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setObject(1, "robin");
ps.executeQuery();
i'm wants print Integrity sql.
For example:select * from person where name='robin'
How should I do?
thanks a lot!PreparedStatement doesn't offer methods for that. You can write your own implementation of PreparedStatement which wraps the originating PreparedStatement and saves the set* values and writes it to the toString().
If needed, myself I just print the sql as well as the values-being-set to the debug statement.Logger.debug(query + " " + values); -
Hi,
I am having some problem using PreparedStatement.executeUpdate() . I want to be able to prepare several queries before commiting and I wrote this just to test it
PreparedStatement stmt= aConnection.prepareStatement("update trans_test1 set field1='a text field' where field1='other text'");
stmt.executeUpdate();
aConnection.commit();
stmt.close();
aConnection.close();
when it hits this line "stmt.executeUpdate();" the program just stops running and after a while throws this error.
java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction
I set the auto commit to false but I still can't get it working and do not understand the problem. Any one can help?
Thanks so much
AlejoHi,
I am having some problem using
PreparedStatement.executeUpdate() . I want to be able
to prepare several queries before commiting and I
wrote this just to test it
PreparedStatement stmt=
aConnection.prepareStatement("update trans_test1 set
field1='a text field' where field1='other text'");
stmt.executeUpdate();This is wrong in so many ways:
(1) Use the bind variables.
(2) Close resources properly in a finally block.
(3) You don't show where you set auto commit to false
(4) You don't show where you rollback in the event of a failure.
>
I set the auto commit to false but I still can't get
it working and do not understand the problem. Any one
can help?A snippet like this isn't enough. Post all the code.
Which database are you using, and which driver?
% -
Doubt in creation of a new object
Hi All,
I have one doubt in creation of a new object.If a new object is to be created and it is not a subtype
of any existing object, then what should we enter in the Program field for creating the object?
I hope I am clear with my question.
Thanks in Advance,
Saket.Hi Saket,
Following will be required for created a custom business object.
1. Object Type - ZTEST (Internal Techincal Key)
2. Object Name - ZTESTNAME (Technical Key Name)
3. Name - TEST (Name of BO, it is used while selecting the object type)
4. Description - (Short Description of BO)
5. Program - ZTESTPROGRAM (ABAP program in which the methods of the object type are implemented)
6. Application - A or B.. etc (Area to which your BO is related)
Please remember that you can learn these basic things by giving F1 help on those fields and in HELP.SAP.COM.
Regards,
Gautham Paspala -
Hi Everyone,
Can we read and validate the attachment of the mail.If so how to do it.
Thanks in advance,
SakthiHi Sakthi,
Please refere the below links:
http://help.sap.com/saphelp_nw2004s/helpdata/en/ad/bf93409c663228e10000000a1550b0/frameset.htm
http://help.sap.com/saphelp_nw2004s/helpdata/en/0d/52b240ac052817e10000000a1550b0/frameset.htm
Let me know if you have any doubts regarding this.
Thanks,
sekhar.
Maybe you are looking for
-
I bought pages for my macbook air, but it is not showing up on my desktop mac
I recently purchased Pages as it is on my ipad / iphone / ipod touch, so I thought why not have it on my Macbook air and desktop mac. I bought it on the Macbook air, but it is not showing up on my purchases, and if I go to download it on the desktop
-
How can i change the apple id on my iphone for icloud?
the iCloud for my new iphone wants to use my old email address and password but i dont remember it. how can i change that.... help!!!!!
-
I have lost sound on my iPad in apps unless I use headphones ,does anyone know how to get sound back without them .I have used the mute volume on the bar at bottom of screen and the slider volume control there only shows when headphones are plugged i
-
I have been importing all my home movies over to a playable format for Itunes. I have found using Cucusoft Apple TV Video Converter was the easiest way for me to do this after trying everything else. I have been able to import successfully a dozen or
-
Which speakers will work on my DVD player?
Hello Recently I bought DVD Player Philips DVP 500 and now I want also to buy 5.1 speakers. DVD player has 1x Digital Audio Coaxial output,so Im thinking of buying Inspire GD580. Is my choice correct one? Since I have nevered bought hardware online,I