For convenience, define two constants first:
Package jmyang. utils; public class constdefine {/*** Weblogic server address */public static final string weblogicserverurl = "T3: // localhost: 7001 "; /*** WebLogic JNDI context string */public static final string weblogicindicontextfactory = "weblogic. JNDI. wlinitialcontextfactory ";}
Encapsulate basic methods such as creating a connection and closing a connection:
Package jmyang. utils; import javax. naming. context; import Java. util. hashtable; import javax. naming. initialcontext; import jmyang. utils. constdefine; import javax. naming. namingexception; import Java. SQL. connection; import javax. SQL. datasource; import Java. SQL. sqlexception; import Java. SQL. statement; import Java. SQL. resultset;/***** <p> title: JDBC tool class </P> * <p> Description: encapsulate common JDBC Operations </P> * <p> copyright: copy Right (c) 2012 </P> * <p> company: yjmyzz.cnblogs.com </P> * @ Author: yjmyzz@126.com * @ version 1.0 */public class JDBC {Private Static Context CTX = NULL;/*** get WebLogic context * @ return context */Public Static Context getcontext () {hashtable ht = new hashtable (); ht. put (context. initial_context_factory, constdefine. weblogicindicontextfactory); ht. put (context. provider_url, constdefine. weblogicserver URL); try {CTX = new initialcontext (HT);} catch (namingexception e) {e. printstacktrace (); return NULL;} return CTX;}/*** get datasource * @ Param dsname string * @ return datasource */public static datasource getdatasource (string dsname) {If (CTX = NULL) {CTX = getcontext ();} If (CTX = NULL | dsname = NULL) {return NULL;} datasource DS = NULL; try {DS = (javax. SQL. datasource) CTX. loo Kup (dsname);} catch (namingexception e) {e. printstacktrace (); return NULL;} return Ds;}/*** get the connection object * @ return connection */public static connection getconnection (datasource DS) {If (DS = NULL) {return NULL;} connection conn = NULL; try {conn = Ds. getconnection ();} catch (sqlexception e) {e. printstacktrace (); return NULL;} return conn;}/*** get the connection object * @ Param dsname string * @ Param Au Tocommittransaction Boolean whether to automatically submit the transaction * @ return connection */public static connection getconnection (string dsname, Boolean autocommittransaction) {If (dsname = NULL) {return NULL ;} datasource DS = getdatasource (dsname); If (DS = NULL) {return NULL;} connection conn = NULL; try {conn = Ds. getconnection (); Conn. setautocommit (autocommittransaction);} catch (sqlexception e) {e. printstacktrac E (); return NULL;} return conn;}/*** get the connection object (automatically submit the transaction) * @ Param dsname string * @ return connection */public static connection getconnection (string dsname) {return getconnection (dsname, true );} /*** close the connection ** @ Param conn connection * @ Param autocommittransaction Boolean whether to automatically submit the transaction */public static void closeconnection (connection Conn, Boolean autocommittransaction) {If (Conn! = NULL) {If (autocommittransaction) {// if the transaction is automatically committed try {Conn. commit ();} catch (sqlexception e) {e. printstacktrace (); try {Conn. rollback ();} catch (sqlexception E2) {e2.printstacktrace () ;}} else {// otherwise, roll back try {Conn. rollback ();} catch (sqlexception E2) {e2.printstacktrace () ;}// close the connection try {Conn. close ();} catch (sqlexception e) {e. printstacktrace () ;}}/ *** close the data connection (and automatically submit the transaction) * @ Param Conn connection */public static void closeconnection (connection conn) {closeconnection (Conn, true );} /*** close the query ** @ Param statement */public static void closestatement (statement) {If (statement! = NULL) {try {statement. close ();} catch (sqlexception e) {e. printstacktrace () ;}}/ *** Execute SQL query * @ Param dsname string * @ Param SQL string * @ return resultset */public static resultset executequery (string dsname, string SQL) {connection conn = getconnection (dsname); If (conn = NULL) {system. out. println ("database connection failed! "); Return NULL;} resultset = NULL; statement cmd = NULL; try {cmd = Conn. createstatement (); resultset = cmd.exe cutequery (SQL);} catch (sqlexception e) {e. printstacktrace () ;}finally {closestatement (CMD); closeconnection (conn);} return resultset ;} /*** Execute SQL update/insert/delete * @ Param dsname string * @ Param SQL string * @ return affects the number of rows */public static int executeupdate (string dsname, string SQL) {int result = 0; connection conn = JDBC. getconnection (dsname); statement cmd = NULL; try {cmd = Conn. createstatement (); Result = cmd.exe cuteupdate (SQL);} catch (sqlexception e) {e. printstacktrace ();} finally {JDBC. closestatement (CMD); JDBC. closeconnection (conn);} return result;}/*** execute an SQL statement (note: the connection is not automatically closed. You need to manually close the conn object after the developer calls it) * @ Param conn connection * @ Param SQL string * @ return int */public static int executeupdate (connection Conn, string SQL) {int result = 0; statement cmd = NULL; try {cmd = Conn. createstatement (); Result = cmd.exe cuteupdate (SQL);} catch (sqlexception e) {e. printstacktrace (); try {Conn. rollback (); // if it fails, try to roll back} catch (sqlexception E2) {e2.printstacktrace () ;}} finally {JDBC. closestatement (CMD);} return result ;}}
the Code below demonstrates basic addition, deletion, modification, query, and transaction usage.
Package jmyang. JNDI; import jmyang. utils. *; import javax. SQL. *; import Java. SQL. *; public class jdbctest {static final string weblogicdatasouecename = "oraclexe";/*** query example */public static void querydemo () {resultset = jdbc.exe cutequery (weblogicdatasouecename, "select * from EMP"); try {While (resultset. next () {system. out. println ("empno =" + resultset. getstring ("empno") + ", ename =" + RE Sultset. getstring ("ename") ;}} catch (sqlexception e) {e. printstacktrace () ;}/ *** add record example */public static void insertdemo () {If (jdbc.exe cuteupdate (weblogicdatasouecename, "insert into dept values ('50 ', 'marketing Department ', 'shanghai') ")> 0) {system. out. println ("insert record successful! ");} Else {system. Out. println (" insert record failed! ") ;}}/**** Deletion example */public static void deletedemo () {If (jdbc.exe cuteupdate (weblogicdatasouecename," delete from Dept where deptno = '50' ")> 0) {system. out. println ("delete record successful! ");} Else {system. Out. println (" delete record failed! ") ;}}/*** Update example */public static void updatedemo () {If (jdbc.exe cuteupdate (weblogicdatasouecename, "Update dept set loc = 'shanghai, China' where deptno = '50'")> 0) {system. out. println ("Update record successful! ");} Else {system. Out. println (" Update record failed! ") ;}}/*** Simple transaction example */public static void transactiondemo () {connection conn = JDBC. getconnection (weblogicdatasouecename, false); // set not to automatically submit the transaction try {jdbc.exe cuteupdate (Conn, "insert into dept values ('50', 'marketing Department ', 'shanghai ') "); jdbc.exe cuteupdate (Conn," insert into dept values ('60', 'Technology Department ') "); // intentionally write less values of a field, and insert fails, cause transaction rollback} catch (exception e) {e. printstacktrace ();} finally {JDBC. closeconnection (conn );}}}
From the code above, we can see that for daily database operations, the executequery (), executeupate () and connection of the statement object are used. setautocommit () basically meets the needs for adding, deleting, modifying, and querying, and transaction calls.
Let's take a look at the calling of the stored procedure:
Create a sample stored procedure in Oracle
Create or replace procedure up_getenamebyno (empno in varchar2, ename out varchar2) isbegin select T. ename into ename from EMP t where empno = empno and rownum = 1; end up_getenamebyno;
It is easy to obtain the ename field value in the EMP table based on empno. The following is the Java call code:
/*** Example of a stored procedure call */public static void proceduredemo () {connection conn = JDBC. getconnection (weblogicdatasouecename); try {callablestatement Statement = Conn. preparecall ("{call up_getenamebyno (?,?)} "); Statement. setstring (1, "7839"); // set the first parameter value to 7839 statement. registeroutparameter (2, types. varchar); // register the second parameter as the return parameter statement.exe cute (); system. out. println (statement. getstring (2); // display returned parameters} catch (sqlexception e) {e. printstacktrace ();} finally {JDBC. closeconnection (conn );}}
Here we use a new object called callablestatement, which is used to call the stored procedure.
Finally, let's take a look at the SQL injection and parameterization issues. As we all know, the query parameters are processed using SQL concatenation. By default, there is a security problem. The following Code demonstrates this:
Public static void querydemo () {string deptno = "'30' or 1 = 1"; resultset = jdbc.exe cutequery (weblogicdatasouecename, "select * from EMP where deptno =" + deptno + "order by ename DESC"); string empno, ename; try {While (resultset. next () {empno = resultset. getstring ("empno"); ename = resultset. getstring ("ename"); deptno = resultset. getstring ("deptno"); system. out. println ("empno =" + empno + ", ename =" + ename + ", deptno =" + deptno) ;}} catch (sqlexception e) {e. printstacktrace ();}}
The Code is intended to find the deptno = 30 record, but eventually it finds all records! (This problem is especially serious when the query parameter value is input from the customer on the front-end interface ). Of course, Java also has a corresponding policy: Use preparedstatement as much as possible and process it in a parameterized manner. The following is the sample code:
/*** Query example (using preparedstatement) */public static void querydemop () {connection conn = NULL; preparedstatement Statement = NULL; string empno, ename, deptno; try {conn = JDBC. getconnection (weblogicdatasouecename); Statement = Conn. preparestatement ("select * from EMP where deptno =? Order by ename DESC "); // pay attention to this? No. Statement. setstring (1, "'30' or 1 = 1"); // set the resultset = statement.exe cutequery (); While (resultset. next () {empno = resultset. getstring ("empno"); ename = resultset. getstring ("ename"); deptno = resultset. getstring ("deptno"); system. out. println ("empno =" + empno + ", ename =" + ename + ", deptno =" + deptno) ;}} catch (sqlexception e) {e. printstacktrace ();} finally {JDBC. closestatement (statement); JDBC. closeconnection (conn );}}
An error is reported during running:
Java. SQL. sqlexception: ORA-01722: Invalid Number
Apparently,Statement. setstring (1, "'30' or 1 = 1 ");The injection is not successful, soWe recommend that you use preparedstatement whenever possible.In terms of efficiency, the preparedstatement is also higher than the statement (many onlineArticleThis includes the introduction of JDBC books, but the actual test results show that the performance does not differ much-in the jdk1.5 + jbuilder2006 + Oracle 11g express + WINXP environment)