1. By reading the file configuration
Packagedatabase operation class; /** Db.java Created on August 20, 2007, Morning 8:37*/ ImportJava.io.*; ImportJava.sql.*; Importjava.util.Properties; Public classDB {PrivateString driver; PrivateString URL; PrivateString User; PrivateString password; PrivateConnection Conn; PrivateStatement stm; PrivateResultSet rs; PublicDB () { This("Dbconf.properties"); } PublicDB (String conf) {loadProperties (conf); Setconn (); } PublicConnection Getconn () {return This. Conn; } //handle the properties file to get the informations for connection Private voidloadProperties (String conf) {Properties props=NewProperties (); Try{props.load (Newfileinputstream (conf)); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } This. Driver = Props.getproperty ("Driver"); This. url = props.getproperty ("url"); This. user = Props.getproperty ("User"); This. Password = props.getproperty ("Password"); } //Implement the Connection Private voidSetconn () {Try{class.forname (driver); This. conn =drivermanager.getconnection (Url,user,password); } Catch(ClassNotFoundException classnotfoundexception) {classnotfoundexception.printstacktrace (); System.err.println ("DB:" +classnotfoundexception.getmessage ()); } Catch(SQLException SQLException) {System.err.println ("Db.getconn ():" +sqlexception.getmessage ()); } } Public voidDoinsert (String sql) {Try{Statement Statement=conn.createstatement (); inti =stm.executeupdate (SQL); } Catch(SQLException SQLException) {System.err.println ("Db.executeinset:" +sqlexception.getmessage ()); } } Public voiddoDelete (String sql) {Try{STM=conn.createstatement (); inti =stm.executeupdate (SQL); } Catch(SQLException SQLException) {System.err.println ("Db.executedelete:" +sqlexception.getmessage ()); } } Public voiddoupdate (String sql) {Try{STM=conn.createstatement (); inti =stm.executeupdate (SQL); } Catch(SQLException SQLException) {System.err.println ("Db.executeupdate:" +sqlexception.getmessage ()); } } PublicResultSet doselect (String sql) {Try{STM=conn.createstatement (java.sql.resultset.type_scroll_insensitive,java.sql.resultset.concur_read_only); RS=stm.executequery (SQL); } Catch(SQLException SQLException) {System.err.println ("Db.executequery:" +sqlexception.getmessage ()); } returnrs; } Public Static voidMain (string[] args) {Try{db db=NewDB (); Connection Conn=Db.getconn (); if(Conn! =NULL&&!conn.isclosed ()) {System.out.println ("Success"); ResultSet RS= Db.doselect ("SELECT * from Content"); while(Rs.next ()) {System.out.println (rs.getstring (1) + ":" +rs.getstring (2) + ":" +rs.getstring (3)); } rs.close (); Conn.close (); } }Catch(SQLException e) {e.printstacktrace (); } } }
java-writing a JDBC operation class