java - Which way is better for update database record? -
i have 2 method update:
string query = "update mytable set name = 'new_value' id ='20' "; connection conn; preparedstatement pstate; try { conn = drivermanager.getconnection(dburl, "root", "2323"); pstate = conn.preparestatement(query); pstate.executeupdate(); } catch (sqlexception sql) { sql.printstacktrace(); }
or:
string query = "update mytable set name = ?" + "where id = ?"; connection conn; preparedstatement pstate; int s; try { conn = drivermanager.getconnection(dburl, "root", "2323"); pstate = conn.preparestatement(query); pstate.setstringt(1, "new_value"); pstate.setstring(2, "20"); s = pstate.executeupdate(); // if s = 1 update done } catch (sqlexception sql) { sql.printstacktrace(); }
both methods update database record correctly, better?
i second approach.
you aren't returning anything, why create result set , go down path?
edit:
even after comment, still use second template. it's more flexible. additionally, it's faster. preparedstatement pre-compiled in database allows database execute parametric query using statement faster normal query. won't happen if use string concatenation (like in first example).
see: http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
additionally, page:
the main feature of preparedstatement object that, unlike statement object, given sql statement when created. advantage in cases, sql statement sent dbms right away, compiled. result, preparedstatement object contains not sql statement, sql statement has been precompiled. means when preparedstatement executed, dbms can run preparedstatement sql statement without having compile first.
although preparedstatement objects can used sql statements no parameters, use them sql statements take parameters. advantage of using sql statements take parameters can use same statement , supply different values each time execute it.
Comments
Post a Comment