First, add, modify, delete, query
Integrate functionality into a class
Packagepb.base;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement;ImportPb.until.ConfigManager; Public classBase { PublicConnection Conn; PublicPreparedStatement pstmt; PublicStatement stmt; PublicResultSet rs; //Establish a connection Public Booleangetconnection () {//get driver,url, user name passwordString Driver = Configmanager.getintance (). GetValue ("Jdbc.driver"); String URL= Configmanager.getintance (). GetValue ("Jdbc.url"); String uname= Configmanager.getintance (). GetValue ("Jdbc.uname"); String pwd= Configmanager.getintance (). GetValue ("Jdbc.upwd"); //(1) Load driver with Class.forName () Try{class.forname (driver); //(2) drivermanager.getconnection (URL, user name, password) Get the connection to the database connection//Oracle Connection Mode Jdbc:oracle:thin: @localhost: 1521:orclconn =drivermanager.getconnection (URL, uname, pwd); } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); return false; }Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); return false; } return true; } //Add, modify, delete Public intexecuteupdate (String sql,object [] pararm) {intUpdaterow=0; Getconnection (); Try{pstmt=conn.preparestatement (SQL); //iterate through an array to set each value for(inti=0;i<pararm.length;i++) {Pstmt.setobject (i+1, Pararm[i]); } UpdateRow=pstmt.executeupdate (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); } returnUpdateRow; } //Enquiry PublicResultSet ExecuteSQL (String sql,object [] pararm) {getconnection (); Try{pstmt=conn.preparestatement (SQL); //iterate through an array to set each value for(inti=0;i<pararm.length;i++) {Pstmt.setobject (i+1, Pararm[i]); } RS=Pstmt.executequery (); } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); } returnrs; } //To close a database connection Public BooleanCloseConnection () {Try { if(rs!=NULL) {rs.close (); } } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); return false; } Try { if(stmt!=NULL) {stmt.close (); } } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); return false; } Try { if(pstmt!=NULL) {pstmt.close (); } } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); return false; } Try { if(conn!=NULL) {conn.close (); } } Catch(SQLException e) {//TODO auto-generated Catch blockE.printstacktrace (); return false; } return true; }}
JDBC Four (Web Foundation learning Note 10)