I am currenting using JDBC to insert data into the SQLServer. I want to select something out from the query, and use the result string as the parameter for the update statement. Please take a brief look on the following code, and please give me some comment so that I can modified it. I know the following style might be sucks.
From the above code, you know I reused the prepare statement variable for both "select" and "insert" query. I am not sure if it's a good practice or not, also, how can I maximize the sql performance here? I want to do better and better.
I wouldn't say that you reused the ps variable, more like you reused the pointer which is just a single value in memory, you're still creating 2 separate objects.
1. Close the ps after you are done with it, it brings huge memory/network benefits
2. Use "static final String" for your SQL statements, and yes create separate pointers for each (no reason to reuse pointer names here).
3. You could use sparate references for the prepared statements (especially because the word Update is included in them) but it won't buy you much performance either way so better to use separate ones for clarity and readibility. In fact, I tend to use the keyword final for 90% of my local variables. It prevents myself from accidently reassigning something throughout a method, ergo, you can always guarentee the updProdStmt relates to an update and never a select.
4. I'm not much for abbreviations, they hard to remember at times. I prefer seeing variable names spelled out when possible.
5. Purely from a rebustness standpoint but you don't have any logic in the case that rs.next() returns false the first time, or true in subsequent times. For example, if you expect exactly one item in the result set, you should throw an exception if rs.next() returns true a second time. You could also check that the value executeUpdate() returns is an int representing that a row or rows was modified. [ June 19, 2006: Message edited by: Scott Selikoff ]