PreparedStatement with BatchUpdate..
Hi to all,
Can anybody provide me as how to proceed for Batch updation with PreparedStatements.
Thanks in advance.
khiz_eng
Hi Shreel,
Many thanx for kind response and solution...
Thanx.
khiz_eng
Similar Messages
-
Ihave a Query that reads a list of materials (1 to many) and a string of delimited numbers. I am currently going through a couple of loops to build my Query string. For example:
WHERE (materials.material = '?' OR materials.material = '?' )........ AND (materials.ONE = '?' "; OR materials.ONE = '?' "; )........
It also involves reading data from two tables: See Query String below:
Query = "Select transactions.control,transactions.date_sent, transactions.date_received, transactions.sender,transactions.recipient,materials.control,materials.material,materials.R,materials.ONE,materials.parent_item,materials.sub_ctrl,materials.quanity FROM transactions LEFT JOIN materials ON transactions.control = materials.control WHERE (LOOP) materials.material = '?' AND (LOOP)materials.ONE = '?' ";
Is it possible to use a preparedstatement with parameters when the number of parameters is unknown until the user selects them?Is it possible to use a preparedstatement withparameters when the number of parameters is unknown
until the user selects them?
masuda1967 is being too Japanese. The answer to your
question is "No".Actually, I would take masuda-san's suggestion--sort of.
You can do the incremental query construction he suggested, but with prepared statements. Something like this. (Note: Probably doesn't match your code exactly, but you should get the idea.)StringBuffer query = new StringBuffer("select ... whatever ...");
for (int ix = 0; ix < numParams; ix++) {
if (x > 0) {
query.append(", ")
query.append(" ? ");
ps = con.prepareStatement(query.toString());
for (int ix = 0; ix < numParams; ix++) {
set the param
} You won't get the performance benefit that can come from using PreparedStatement, but you still avoid the headache of escaping strings, formatting dates, etc.
ジ -
PreparedStatement with a mssqlserver4v65 DataSource
We have been trying to boost our performance by using PreparedStatement
with the WLS MSSQL Driver, but gained none. Are any of you out there
using PreparedStatements with that driver and noticing performance
improvement?
On a related note, what could we possibly do so wrong with that driver
that would annihilate the performance boost we should have gained? If we
switch to another driver with the exact same code, we see that we gain a
noticable performance gain thanks to the use of PreparedStatements.
Any idea?
Thanks,
ChristopheThanks for your active feedback, Slava. Joe explained everything in
another email in this thread.
And Joe, since you seem to read every post, a BIG THANKS to you too!
Christophe
Slava Imeshev wrote:
Christophe,
First, you have to close result set explicitly.
Second, you say you don't see performance gain.
What did you use to compare performance of prepared
statement?
Regards,
Slava Imeshev
"Christophe Warland" <christophe.warland_REM@OVE_s1.com> wrote in message
news:3C60270F.4060900@OVE_s1.com...
We are using WLS 6.1 SP1.
Our code is actually part of a huge piece of our architecture, so I can
not easily give something to you that would compile on your machine. But
it would look like the following excerpt. 'runTest' acquires a
connection from a JNDI DataSource, creates a PreparedStatement and then
loops on 'testItSingle'.
public long runTest() throws Exception {
long start = System.currentTimeMillis();
// acquire connection from JNDI datasource
// (not shown here)
Connection con = getConnection();
String sql = getSql();
PreparedStatement st = con.prepareStatement(sql);
for (int i = 0; i < TEST_LEN; ++i) {
testItSingle(i, st);
close(st);
close(con);
long end = System.currentTimeMillis();
return end - start;
protected void testItSingle(int i, PreparedStatement st)
throws Exception {
String[] elem = DATA;
String p1 = elem[0]; // acct id
String p3 = elem[1]; // prod code
st.setString(1, p1);
st.setLong(2, ISOCode);
st.setString(3, p3);
ResultSet rs = st.executeQuery();
protected String getSql() {
return "SELECT A.versionStamp AS aLockValue, B.versionStamp AS
bLockValue, A.VFMAcctKy, A.SECEntityKy, A.VFMProductKy, A.acctID,
A.ISOCurrencyCdKy, A.isSrcXferEnabled, A.isDestXferEnabled,
A.maxXferAmt, A.minXferAmt, A.maxPmtAmt, A.minPmtAmt, A.versionStamp,
ledgerBal, ledgerBalDttm, availBal, availBalDttm, overdraftBal,
overdraftBalDttm, ytdInt, ytdIntDttm, lstYrInt, lstYrIntDttm, sumField1,
sumField2, sumField3, sumField4, sumField5, sumField6, sumField7,
sumField8, sumField9, sumField10, sumField11, sumField12, sumField13,
sumField14, sumField15, sumField16, sumField17, sumField18, sumField19,
sumField20 , E.VFMProdSubTypeKy, null VFMCustomerKy FROM VFMAcct A,
VBMDepositAcct B, VFMProduct E WHERE A.VFMAcctKy = B.VFMAcctKy AND
E.VFMProductKy = A.VFMProductKy AND A.acctID = ? AND A.ISOCurrencyCdKy =
? AND E.productCode = ? ORDER BY E.VFMProdSubTypeKy";
We also try to close statement and result set inside 'testItSingle' but
it didn't imporve anything. The preparedstament was actually reopened
silently and running just fine.
Thanks for your help,
Christophe
Slava Imeshev wrote:
Christophe,
Which version of weblogic and service pack do you use?
Could you show us your questionable code? -
BindVariables and PreparedStatement with sysdate
Hi
I,m using PreparedStatements to update the DB (8.1.7) but battle with the sysdate. Here is code snippet:
stringBuff = new StringBuffer("INSERT INTO so_cs.tc48_event_details ");
stringBuff.append("(cc48_event_ref_no, ");
stringBuff.append("cc48_call_cat_code, ");
stringBuff.append("cc48_call_cat_item_code, ");
stringBuff.append("cc48_action_number, ");
stringBuff.append("cc48_user_id, ");
stringBuff.append("cc48_date_modified, ");
stringBuff.append("cc48_machine_name, ");
stringBuff.append("cc48_action_status)");
stringBuff.append(" VALUES ");
stringBuff.append("(?,?,?,?,?,sysdate,?,?)");
int startAct = 1;
String eveStatus = "C";
update = stringBuff.toString();
pstmt4 = conn.prepareStatement(update);
((OraclePreparedStatement)pstmt4).setInt(1,eventRefNo);
((OraclePreparedStatement)pstmt4).setInt(2,callCatCode);
((OraclePreparedStatement)pstmt4).setInt(3,callCatItemCode);
((OraclePreparedStatement)pstmt4).setInt(4,startAct);
((OraclePreparedStatement)pstmt4).setInt(5,operatorId);
((OraclePreparedStatement)pstmt4).setString(6,machineName);
((OraclePreparedStatement)pstmt4).setString(7,eveStatus);
With the value of sysdate in the update string, it generates a new SQL statement in the sga causing a statement parsing for each statement.
How do I convert a java date into the setDate(int, Date) format to set the value for sysdate with the ? variable bind?
Tks
AndreHi Andre,
It's because of how java handles dates (and times). What we do at my place of work is set the default time zone for the JVM when we first start it up.
Here is the code I use (with java versions 1.4.1 and 1.3.1):
TimeZone l_defaultTimeZone = TimeZone.getDefault();
int l_rawOffset = l_defaultTimeZone.getRawOffset();
String l_id = l_defaultTimeZone.getID();
SimpleTimeZone l_simpleTimeZone = new SimpleTimeZone(
l_rawOffset,
l_id,
0,
0,
0,
0,
0,
0,
0,
0);
TimeZone.setDefault( l_simpleTimeZone );Hope this helps.
Good Luck,
Avi. -
PreparedStatement with 56cols in batch giving ArrayIndexOutOfBoundException
Hello All,
PreparedStatement trying to do bath update/inserts in table with 56 columns is giving ArrayIndexOutOfBoundException sporadically with 11.2.0.3 driver. Is it related to Bug 6396242,which was supposed fix in 11.1.0.7.0?
Here is the stackTrace:
EXCEPTION ENCOUNTERED:
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 4
at oracle.jdbc.driver.VarnumBinder.big5pow(OraclePreparedStatement.java:15348)
at oracle.jdbc.driver.VarnumBinder.constructPow52(OraclePreparedStatement.java:15420)
at oracle.jdbc.driver.VarnumBinder.dtoa(OraclePreparedStatement.java:15884)
at oracle.jdbc.driver.DoubleBinder.bind(OraclePreparedStatement.java:17239)
at oracle.jdbc.driver.OraclePreparedStatement.setupBindBuffers(OraclePreparedStatement.java:3137)
at oracle.jdbc.driver.OraclePreparedStatement.processCompletedBindRow(OraclePreparedStatement.java:2355)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3579)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3665)Welcome to the forum!
>
PreparedStatement trying to do bath update/inserts in table with 56 columns is giving ArrayIndexOutOfBoundException sporadically with 11.2.0.3 driver. Is it related to Bug 6396242,which was supposed fix in 11.1.0.7.0?
>
How would anyone know? You haven't posted the 4 digit Oracle version, the JDK version, the platform or any code for anyone to look at.
Post the code and other information people need to try to help you. -
PreparedStatement with wildcard
Hi all I am sure this is simple but it's not obvious to me at the moment.
With a preparedStatement I have I the first time I call it it needs 3 parameters, if I don't get a result from this then I need to do the same call again with only the first 2 parameters being important (I want the third one to match on everything).
for some reason I thought putting in "*" as the string to search for would work - don't ask why, upon encountering the error I realized how dumb that would be. I am trying to find out if there is a generic wildcard for this or is it something that varies from driver to driver ? Is what I want to do even possible ? I can do it by re-creating the statement with the new query that is one shorter but that would not be favorable at all as the above is the toy case in actuality to what is needed.
as always thanks for any advice on the matter.I usually* approach this by doing an:
WHERE ((x = ?) or (? is null)) ...Then I set both of those parameters to the check value, OR null if I don't care.
The downside is that you have to set twice as many parameters.
The up side is that you can use the same prepared statement regardless of whether you want to do the check.
And of course an = check doesn't work if the parameter is null anyway, so that's not an issue.
*Actually I'm using an HQL named query with named parameters which eliminates some of the work, but that's what it boils down to underneath the covers. -
PreparedStatements with parameters inside functions
With PreparedStatements, can I use parameters inside of functions. For example, instead of doing:
stmt = conn.prepareStatement("INSERT INTO MyTable (EncData) VALUES (ENCRYPTBYKEY(KEY_GUID('MyKey'), 'ABCDEF''))");
I want to do:
stmt = conn.prepareStatement("INSERT INTO MyTable (EncData) VALUES (ENCRYPTBYKEY(KEY_GUID('MyKey'), ?))");
stmt.setString(1, "ABCDEF");
I am getting a 'String or binary data would be truncated' exception when trying this.
Thanks,
KevinOK ... let me take you a couple steps back ...
I can get PreparedStatements to work in Java (J2SE1.5):
stmt = conn.prepareStatement("INSERT INTO MyTable (Data) VALUES (?)");
stmt.setString(1, "ABCDEF");
However, the previous example does not work through SQL Server Management Studio ... it gives a syntax error:
INSERT INTO MyTable (Data) VALUES (?)
Moving onto my issue, how do I get PreparedStatement parameters to work within a function:
stmt = conn.prepareStatement("INSERT INTO MyTable (EncData) VALUES (ENCRYPTBYKEY(KEY_GUID('MyKey'), ?))");
stmt.setString(1, "ABCDEF");
And as mentioned earlier, the following works fine in Java J2SE 1.5
stmt = conn.prepareStatement("INSERT INTO MyTable (EncData) VALUES (ENCRYPTBYKEY(KEY_GUID('MyKey'), 'ABCDEF'))");
So, in conclusion:
I can successfully make PreparedStatements perform inserts using parameters in Java
I can successfully make PreparedStatements perform inserts in Java using the encryption function
However, I cannot make PreparedStatements perform inserts using parameters in the encryption function in Java
I cannot get a simple example of PreparedStatements to work in SQL Server Management Studio ... and wouldn't expect to ...
Thanks,
Kevin -
Caching PreparedStatements with DB2
I was using Statements, and my DB2 admin says that every call is invoking a prepared statement on the DB side. I learned that PreparedStatements can be cached, so I switched to using that method. However, I see ABSOLUTELY NO database performance increase. Does my DB admin need to turn caching on or do something to allow the code to use caching?
The only place where extended dynamic was mentioned was in the Application Development Guide, and it says this:
DB2 for VSE & VM extended dynamic SQL statements are rejected with -104
and syntax error SQLCODEs. -
PreparedStatement with IN clause
Hi,
I have a question regarding using a PreparedStatement and a query
using an IN clause.
I need to pass an array of values to using an IN clause. How does the
binding work in this case since I am getting an SQLException - Invalid
column type ?
I need to pass an array of longs to this query.
The java.sql.Array does not have an implementation. How does this do
this ?Aswin Dinakar wrote:
>
Thanks a lot ! You really understood my problem without me describing it
properly.
I dont mind keeping it as a statement but that statement is being executed in
a FOR loop thousands of times and its a very complex SQL with lots of joins
and its taking up a lot of the CPU. Time constraint prevent me from changing
the business logic.I also suggest making a stored procedure to do the complex stuff. At least the
DBMS will only have to parse it once. The argument could even be a string
like "1,2,3,4,5,6", and the procedure could handle separating the values.
In a related issue do you know if the JMS database updates(deletes mostly) for
WLS 5.1 are PreparedStatement(s) ? When I query the v$sqlarea table for the
parse counts I see lots of JMS updates to the database.yes they are, but our MS SQLServer driver is inefficient about SQL with
PreparedStatements, sending fresh SQL to be parsed each execution. I suggest
your trying the MS driver from www.inetsoftware.de, which will do a better jod
than ours in this area.
Joe
>
Joseph Weinstein wrote:
A PreparedStatement only allows settable parameters representing
single values. You can't do:
stmt = c.prepareStatement("select * from foo where key in ?");
stmt.setString(1, "(1,2,3,4,5,6)");
Therefore, you need to know how many values in your In clause,
and generate a PreparedStatement like:
stmt = c.prepareStatement("select * from foo where key in (?,?,?,?,?...");
with a '?' for every value. Depending on whose driver your using, and
whether you can keep and re-use PreparedStatments, it might be better
to simply make the whole SQL query as a simple string and execute it:
String query = "select * from foo where key in (1,2,3,4,5,6)";
rs = stmt.executeQuery(query);
Aswin Dinakar wrote:
Hi,
I have a question regarding using a PreparedStatement and a query
using an IN clause.
I need to pass an array of values to using an IN clause. How does the
binding work in this case since I am getting an SQLException - Invalid
column type ?
I need to pass an array of longs to this query.
The java.sql.Array does not have an implementation. How does this do
this ? -
JDBC PreparedStatement with Oracle 8.0.5 on Linux
As the subject stated, I am using Oracle 8.0.5 on a Linux machine.
When I am using a PreparedStatement, somehow, the binded variables are reversed in order.
E.g.
String sql = "INSERT INTO TABLE1 (X, Y) VALUES (?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "1");
ps.setString(2, "2");
ps.executeUpdate();
When I run the above, the insertion is successful. However, when I select the table, this is what I get.
X Y
2 1
The values are reversed.
This is the same for update statement too.
If I do this,
"UPDATE TABLE1 SET X = ? WHERE Y = ?"
ps.setString (1, "3");
ps.setString (2, "1");
The above will not be successful.
If I do this,
ps.setString (2, "3");
ps.setString (1, "1");
The above is successful.
Somehow the order of the binded variable get messed up.
Does anyone has any idea why?The datatype of X and Y are both VARCHAR2(10) in this case.
Even if they are numbers, they have the same problem. The order get reversed and the data inserted is incorrect.
E.g. I have column M VARCHAR2(10) and column N NUMBER (2) in TABLE2.
String sql = "INSERT INTO TABLE2 (M, N) VALUES (?, ?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "one");
ps.setInt(2, 1);
ps.executeUpdate();
The insert operation is still successful. But when you select it becomes,
M N
? 0
This is because the order of the variables get reversed again.
Forgot to mention that if we have used Statement instead of PreparedStatement, we will not have such problem.
E.g. Statement stmt = conn.createStatement();
String sql = "INSERT INTO TABLE2 (M, N) VALUES ('one', 1)";
stmt.executeUpdate(stmt);
The above will insert fine and when we do a select, the result is correct.
M N
one 1
Though the above works fine, I still prefer to use PreparedStatement because of performance issue. So anyone has any idea what exactly is happening?
Hmmm, this ones a strange one.
What type are X and Y in the database? If they are of
type NUMBER why not try something like.
ps.setInt(1, 1);
OR
ps.setLong(2, 2);
and see if that makes any difference. -
Hi All,
I am trying to to batch update with CallableStatement.
First I set autocommit off.
Then in the while loop and add the batch statement to my CallableStatement
after the loop I call executeBatch on CallableStatement which returns an array of int.
At the end I do a commit.
Eventhough I am adding multiple records for batch update,the value of the array of int is only 1 which means only 1 record is updated. I verified in the database that,it is updating only one record no matter how many records I set for batch update.
Did anyone run into same issue?
ThanksFirst I get the data from another database through the resultset orderDetailsResultSet and then I do the following
conn.setAutoCommit(false);
while(orderDetailsResultSet.next())
addOrderDetailStatement = conn.prepareCall("begin
ORDER_PROCESS.add_order_detail( ?, ?, ?, ? ,? ,?); end;" );
addOrderDetailStatement.setString(1,orderNum);
addOrderDetailStatement.setString(2,orderDetailsResultSet.getString("Detail_seq_num")); addOrderDetailStatement.setString(3,orderDetailsResultSet.getString("Item_num")); addOrderDetailStatement.setString(4,orderDetailsResultSet.getString("Tie_num")); addOrderDetailStatement.setInt(5,orderDetailsResultSet.getInt("Order_qty")); addOrderDetailStatement.setString(6,orderDetailsResultSet.getString("Item_class"));
addOrderDetailStatement.addBatch();
int[] noOfRowsAffected = addOrderDetailStatement.executeBatch();
conn.commit(); -
PreparedStatement with IN sql clause
Hi guyz,
Need ur advice once again...
I am using JDBC 2.0 thin sql driver.
I want a number column in db called TICKET_NUMBER
Here is my problem.
String sql = "select * from TICKETS where TICKET_NUMBER in ?";
ps = edbCon.prepareStatement(sql);
ps.setString(1,"100,200");
Can I do this? Its not working. So does that mean PreparedStatements doesnot support IN clause of the sqls. Help me out.
-RamHi guyz,
Need ur advice once again...
I am using JDBC 2.0 thin sql driver.
I want a number column in db called TICKET_NUMBER
Here is my problem.
String sql = "select * from TICKETS where
here TICKET_NUMBER in ?";
ps = edbCon.prepareStatement(sql);
ps.setString(1,"100,200");
Can I do this? Its not working. So does that mean
PreparedStatements doesnot support IN clause of the
sqls. Help me out.
-RamIt will work, but you have to have: where TICKET_NUMBER IN (?,?,?). You'll have to build the last part dynamically based on the number of parameters that you have. Be carefull too, certain database implementations have a limit on the number items that you can include in the IN clause.
You'll also have to loop through and do your parameter sets.
Paul -
Preparedstatement with two tables
I try to use "preparedstatement" to insert two tables. Is there any posibility to control the constraint of the two tables? Assume that the two tables are master detail. Commit them both or rollback them both... An example would be very helpful.
Something like that: if the preparedstatement2 throws an exception then I should rollback the preparedstatement1.
StringBuffer stringbuffer = new StringBuffer();
stringbuffer.append("insert into T_ABC");
stringbuffer.append("(a,b,c)");
stringbuffer.append(" VALUES(?, ?, ?);
StringBuffer stringbuffer2 = new StringBuffer();
stringbuffer2.append("insert into T_DEF");
stringbuffer2.append("(d,e,f,g)");
stringbuffer2.append(" VALUES(?, ?, ?, ?);
preparedstatement1 = dc.prepareStatement(stringbuffer.toString());
preparedstatement2 = dc.prepareStatement(stringbuffer2.toString());
preparedstatement1.setLong(1, 0);
preparedstatement1.setLong(2, 0);
try {
preparedstatement1.executeUpdate();
preparedstatement2.executeUpdate();
} catch {
//control
} -
Keep Oracle DATE datatype but insert via PreparedStatement with time
I know there are alot of messages concerning java.sql.Date and that it doesn't
hold the time.
Can you give me an example of how to insert Date and Time into an Oracle
"DATE" field using preparedStatements?
dailysunjava.util.Date d = new java.util.Date();
java.sql.Timestamp ts = new java.sql.Timestamp(d.getTime());
prepStatement.setTimestamp(1, ts); -
Suggestion regarding running preparedstatement and batchupdate
I have to insert many rows in database therefore i use preparedstatement and for loop.I want to know if i add all the query in batch and then execute will it give better performance .Will sql statement is still in compiled form when execute in batch .Let if i add another sql statement which is different from previous sql statement in batch what the effect it has on performance.
Thankshi.,
check this out..
http://forum.java.sun.com/thread.jspa?threadID=154870&start=15&tstart=0
Maybe you are looking for
-
802.1X wirelss restriction on User Login policies
Hi all, Seeking some technical idea on Wireless 802.1x setup. Business requirement is: "User login policy: to limit the number of concurrent login by a single user only apply to one device at any given time. " There is no problem on PEAP/MSCHAPv2 log
-
Hi Any One! How do I export style code from a DW document in Dreamweaver CS3?
-
Panic problems, unexplained beep, and flash player keeps quitting
I just bought my first mac computer 3 months ago and was given a new one a couple weeks ago because there were some issues with the first mac but those issues were nothing compared to what's happening with this second computer. First of all, I like t
-
Problem with CALC_DUMMY_ORG
I can't get CALC_DUMMY_ORG to work on rollup members and I would like suggestions on how I can debug the problem. My logic looks like this (thanks Joost). Note: DEPARTMENT is of type ENTITY: *XDIM_MEMBERSET ACCOUNT=<ALL> *XDIM_MEMBERSET DEPARTMENT=<
-
TS4006 Can I turn on "Location Services" via the cloud on a lost ipad?
Can I turn on "Location Services" via the cloud on a lost Ipad?