JDBC 4 (web basic learning notes 10) and jdbc learning notes
1. Add, modify, delete, and query
Integrate functions into a class
Package pb. base; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. preparedStatement; import java. SQL. resultSet; import java. SQL. SQLException; import java. SQL. statement; import pb. until. configManager; public class Base {public Connection conn; public PreparedStatement pstmt; public Statement stmt; public ResultSet rs; // create a Connection public boolean getConnection () {// get DRIVER, url, username and password St Ring 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) Use Class. forName () load driver try {Class. forName (driver); // (2) DriverManager. getConnection (URL, user name, password) to obtain the Connection of the database // Oracle Connection method jdbc: orac Le: thin: @ localhost: 1521: orcl conn = DriverManager. getConnection (url, uname, pwd);} catch (ClassNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace (); return false;} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace (); return false;} return true;} // Add, modify, delete public int executeUpdate (String SQL, Object [] pararm) {int UpdateRow = 0; getConnection (); Try {pstmt = conn. prepareStatement (SQL); // traverse the array to set each value for (int I = 0; I <pararm. length; I ++) {pstmt. setObject (I + 1, pararm [I]);} UpdateRow = pstmt.exe cuteUpdate ();} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace ();} return UpdateRow;} // query public ResultSet executeSQL (String SQL, Object [] pararm) {getConnection (); try {pstmt = conn. prepareStatement (SQL); // traverses the array to set each value for (I Nt I = 0; I <pararm. length; I ++) {pstmt. setObject (I + 1, pararm [I]);} rs = pstmt.exe cuteQuery ();} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace () ;}return rs ;}// close the database connection public boolean CloseConnection () {try {if (rs! = Null) {rs. close () ;}} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace (); return false;} try {if (stmt! = Null) {stmt. close () ;}} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace (); return false;} try {if (pstmt! = Null) {pstmt. close () ;}} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace (); return false;} try {if (conn! = Null) {conn. close () ;}} catch (SQLException e) {// TODO Auto-generated catch block e. printStackTrace (); return false;} return true ;}}