Jdbc
-One, JDBC connection process
01. Registration Driver
Class.forName ("Oracle.jdbc.driver.OracleDriver");
02. Get the Connection
Connection conn = drivermanager.getconnection ("Jdbc:oracle:thin:@10.0.19.252:1521:orcl", "Itxy", "Itxy");
-Two, JDBC common interface
Specification of the Access database provided by Jdbc:sun
This set of specifications for high-speed database vendors, how to access their databases
01.java.sql Interface Connection
Sun's JDBC is a set of interface specifications that do not provide implementations (JDBC interface implementations can only be implemented by individual database vendors themselves)
02.java.sql
The Statement interface is used to execute a static SQL statement and return the object to which it produces results.
java.sql
Interface PreparedStatement An object that represents a precompiled SQL statement.
Note: When developing, first PreparedStatement
Cause: 1. Objects with precompiled SQL statements run faster
2. Security (can prevent SQL injection attacks)
03.java.sql Interface ResultSet
A data table that represents a database result set, typically generated by executing statements that query the database.
ResultSet
Object has a cursor that points to its current data row. Initially, the cursor is placed before the first line. next
method moves the cursor to the next line, because the method ResultSet
returns when the object has no next line false
, so it can be used in a while
loop to iterate over the result set.
The default ResultSet
object is not updatable, there is only one cursor that moves forward. Therefore, it can only be iterated once, and only in the order from the first row to the last row.
-Three. JDBC uses common exceptions
Java.lang
Class class<t>
Java.lang.ClassNotFoundException:oracle.jdbc.driver.OracleDriver2
Database driver not loaded successfully
Java.sql.SQLException:The Network Adapter could not establish the connection
Database connection String Configuration error
Java.sql.sqlexception:ora-01017:invalid Username/password; Logon denied
Wrong user name or password to access the database
Summary of exceptions
1. Exception processing order, must be subclass exception handling before, the parent class exception handling after
try {biz.deletestudent ("s002"); System.out.println ("delete finished!");} catch (Sqlintegrityconstraintviolationexception e) {} catch (Exception e) {e.printstacktrace (); SYSTEM.OUT.PRINTLN ("System exception, please check");}
2. In a three-tier architecture, exceptions can occur for each layer, but only the UI layer takes the final decision to display the exception.
Other layers can catch exceptions, but they need to be thrown again after processing!
3. Unmanaged resources (resources that are not managed by GC) must be released in finally and placed on resource leaks;
Resources that are not managed by GC: such as data connection connection, you must use the close () method to release
There is also the release of the IO stream, which must also use close ()
try {}finally{dao.closeconnection ();}
4. Custom Exceptions
public class Havasonrecordsexception extends exception{public havasonrecordsexception (String msg) {super (MSG); }}
5. Java.lang class Throwable
Directly known subclasses:
Error, Exception
Error is a subclass of Throwable that is used to indicate a serious problem that a reasonable application should not attempt to capture.
Note: Error does not require a try Catch
Example of error exception: Memory out of bounds, memory overflow
6. Try catch can be nested using the
7. Only try, no catch
try {dao.updatestustate (0, Sno);} finally{//disposes the handle of the IO stream System.out.println ("IO resource release");}
8. Checked Exception and unchecked Exception (Runtime Exception)
Checked Exception (feature: At compile time you can identify where the exception might occur and you must capture it):
ClassNotFoundException
SQLException
Runtime Excepiton (This exception cannot be checked at compile time, only known during program run time):
Nullexcepiton, 10/0, Format ("")
public class Inputnullexcepiton extends runtimeexception{}//runtimeexception no mandatory handling of public class Inputnullexcepiton Extends exception{}//Custom exception, recommended extends Exception
Database connection is a valuable resource that can easily be called a performance bottleneck for business systems
principle of Use:
Open late, early off-----use less time better
Connection try to reuse
The number of database connection is not unlimited, it is limited by the hardware (CPU)
Tween
Java.util class Date//except the DAO layer, try to use Java.util.Date
java.sql class Date//can only be used on the DAO layer
Exercise (Java Project):
Custom exceptions
public class Inputnullexception extends Exception {public inputnullexception (String msg) {super (MSG);}}
web layer
public class stuui {/** * Delete Student */public static void deletestutest () {stubiz biz = new stubiz (); Try {biz.deletestudent ("s003234"); System.out.println ("delete finished!");} catch (exception e) {e.printstacktrace (); SYSTEM.OUT.PRINTLN ("System exception, please check");}} /** * Add Student */public static void addstutest () {stubiz biz = new stubiz (); Tstudent ts = new tstudent (); Ts.setsname ("Jack"), Ts.setsno ("s002244"); Ts.setcno ("c0124"); Ts.setsex ("F"); Ts.setaddress ("Taiyuan"); Ts.settel ("155345263"); string s = "2012-06-21"; Simpledateformat sdf = new simpledateformat ("Yyyy-mm-dd"); java.util.date d1 = null;try {d1 = sdf.parse (s);} catch (PARSEEXCEPTION&NBSP;E1) {e1.printstacktrace ();} //the string to util first. Date Object Java.sql.date d2 = new java.sql.date (D1.gettime ()); ts.setbirthday (d2); ts.setheight, ts.setstate (1); Try {biz.addstu (TS); System.out.println ("Add Student success!") ");} catch (inputnullexception e) {System.out.println ("entry is empty! ");} catch (exception e) {e.printstacktrace (); System.out.println ("Insert failed! ");}} /** * Query All Student Information */public static void showstu () {stubiz biz = new stubiz (); Try {list<tstudent> stus = biz.findallstu ();Iterator<TStudent> it = stus.iterator (); while (It.hasnext ()) { Tstudent t = it.next (); system.out.println (T.getSname () + "--" + t.getsno () + "--" + t.getbirthday ()); }} catch (exception e) {e.printstacktrace (); SYSTEM.OUT.PRINTLN ("Query failed! ");}} Public static void main (String[] args) {stuui.showstu ();}}
Business Logic Layer:
public class stubiz {/** * Delete students * Note: 1. Delete Physical records directly when students do not produce business data * 2. when students generate business data, they can only do tombstone * @param sno * @throws exception */public void deletestudent ( String sno) throws exception{if (sno != null) {studao dao = new Studao (); try {dao.deletestudent (SNO);} catch (java.sql.sqlintegrityconstraintviolationexception e) { if (E.getsqlstate (). Equals ("23000") { //found the child record try { dao.updatestustate (0, sno); } catch (Exception e2) { e2.printstacktrace (); throw e2; } Finally{ dao.closeconnection (); } }} catch (Exception e) {throw e;} Finally{dao.closeconnection ();}} Else{throw new exception ("Incoming parameter error, sno=null");}} /** * Add students * @param ts * @throws exception */public void addstu (tstudent ts) throws exception{if (ts!=null) {studao dao = new Studao (); Try {boolean bet = dao.findclass (Ts.getcno ()); if (!bet) {throw new Exception ("Class does not exist");} Else{dao.addstu (TS);}} catch (Exception e) {throw e;} Finally {dao.closeconnection ();}} Else{throw new exception ("Incoming parameter Error! ");}} /** * Check all student information * @return * @throws Exception */public List< Tstudent> findallstu () throws exception { //Note: interface-oriented programming cannot be an implementation class return list<tstudent> stus; Studao dao = new studao (); Try {stus = dao.findallstu ();} catch (Exception e) {throw e;} Finally {dao.closeconnection ();} Return stus;}}
data layer:
public class studao extends basedao{/** * Delete students * Note: 1. Delete Physical records directly when students do not generate business data * 2. When a student generates business data, it can only be tombstoned * @param sno * @throws exception */public void deletestudent (String sno) throws Exception{String sql = "Delete from tstudent where sno=? "; This.openconnection (); Preparedstatement ps = this.conn.preparestatement (SQL);p s.setstring (1,&NBSP;SNO); Ps.executeupdate ();p s.close ();} /** * Modify students ' status values * @param state * @throws Exception */public Void updatestustate (Int state,string sno) throws exception{string sql = "update tstudent set state=? where sno="; This.openconnection (); Preparedstatement ps = this.conn.preparestatement (SQL);p S.SEtint (1, state);p s.setstring (2, sno);p s.executeupdate ();p s.close ();} /** * Add students * @param ts * @throws exception */public void addstu (tstudent ts) throws Exception {String sql = "Insert into tstudent values (?,?,?,?,?,?,?,?,?) "; /Database open this.openconnection (); Preparedstatement ps = this.conn.preparestatement (SQL);p s.setstring (1, ts.getSname ()); Ps.setstring (2, ts.getsno ());p s.setstring (3, ts.getcno ());p s.setstring (4, ts.getsex ()); Ps.setstring (5, ts.getaddress ());p s.setstring (6, ts.gettel ());p s.setdate (7, ts.getbirthday ()); Ps.setint (8, ts.getheight ());p S.setint (9, ts.getstate ());p s.executeupdate ();p s.close (); /** * When adding students, check if the class exists * @param cno * @return * @throws Exception */public boolean findclass (STRING&NBSP;CNO) throws exception {boolean bret = false; string sql = "select * from tclass where cno=?"; This.openconnection (); Preparedstatement ps = this.conn.preparestatement (SQL);p s.setstring (1,&NBSP;CNO); Resultset rs = ps.executequery (); while (Rs.next ()) {bret = true;} Rs.close ();p s.close (); return bret;} /** * Check all student information * @return * @throws Exception */public List< Tstudent> findallstu () throws exception {list<tstudent> stulist;//writes two lines of string sql = "select * from tstudent";//written before OpenConnection this.openconnection (); Preparedstatement ps = this.conn.preparestatement (SQL); Resultset rs = ps.executequery ();stulist = new arraylist<tstudent> ();// This will not result in memory allocation if the previous error (Rs.next ()) {tstudent ts = new tstudent ();//new tstudent () is to create a new memory, this will not be released, except that each time an object reference is established Ts.setsName (rs.getstring ("sname")), Ts.setcno (rs.getstring ("CNO")), Ts.setsno (rs.getstring ("Sno")), Ts.setaddress ( Rs.getstring ("Address")), Ts.setsex (rs.getstring ("Sex")), Ts.settel (Rs.getstring ("tel")); Ts.setbirthday ( Rs.getdate ("Birthday")), Ts.setheight (Rs.getint ("height")), Ts.setstate (Rs.getint ("state")), Stulist.add (TS);// The collection contains a reference, add to the collection, copy the object address, and then release the object Address}rs.close ();p s.close (); return stulist;}}
Basedao
public class Basedao {protected Connection conn;public void OpenConnection () throws exception{//through reflection technology, The Oracel driver object is loaded (actually doing type checking)//When the class is loaded, the static code block in Oracledriver is called and the static variable is initialized Class.forName (" Oracle.jdbc.driver.OracleDriver "); conn = Drivermanager.getconnection ("Jdbc:oracle:thin:@10.0.19.252:1521:orcl", "Itxy", "Itxy");} public void CloseConnection () {if (this.conn! = null) {try {this.conn.close ();} catch (Exception e) {e.printstacktrace ();}} }}
This article from "Qin Bin blog" blog, declined reprint!
JDBC and exception summary and common use