The DAO pattern is a design-time-oriented pattern for Java. And DAO in the Basedao is nothing but the data to curd (increase the deletion check), the following is the most common connection, add and remove the method of change.
1 PackageDAO;2 3 ImportJava.sql.*;4 5 /**6 * Database Access class7 */8 Public classBasedao {9 //Database-drivenTen Private StaticString Driver = "Com.mysql.jdbc.Driver"; One //Database Connection Address A Private StaticString url = "Jdbc:mysql://127.0.0.1:3306/flight?usessl=false"; - //Database user name - Private StaticString user = "root"; the //Database Password - Private StaticString password = "123456"; - - //Database Connection + protectedConnection conn =NULL; - //Statement Object + protectedPreparedStatement pstmt =NULL; A at /** - * Connect to database - * - * @returnDatabase Connection - * @throwsClassNotFoundException Driver class exception not found - * @throwsSQLException Database Exceptions in */ - protectedConnection Getconn ()throwsClassNotFoundException, SQLException { to //Load Driver + Class.forName (driver); - //Get Connections theconn =drivermanager.getconnection (URL, user, password); * returnConn; $ }Panax Notoginseng - /** the * Database Query method + * A * @paramSQL pre-compiled SQL statements the * @paramparams pre-compilation parameters + * @returnQuery Result set - * @throwsSQLException Database Exceptions $ */ $ protectedResultSet executequerysql (String sql, object[] params)throwsSQLException { -ResultSet rs =NULL; - Try { theconn =getconn (); -}Catch(ClassNotFoundException e) {Wuyi e.printstacktrace (); the } -PSTMT =conn.preparestatement (SQL); Wu if(Params! =NULL) { - for(inti = 0; i < params.length; i++) { AboutPstmt.setobject (i + 1), Params[i]); $ } - } -rs =pstmt.executequery (); - returnrs; A } + the /** - * Database additions and deletions modified method $ * the * @paramSQL pre-compiled SQL statements the * @paramparams pre-compilation parameters the * @returndatabase affects row count the * @throwsSQLException Database Exceptions - */ in protected intExecuteupdate (String sql, object[] params)throwsSQLException { the Try { theconn =getconn (); About}Catch(ClassNotFoundException e) { the e.printstacktrace (); the } the intnum = 0; +PSTMT =conn.preparestatement (SQL); - if(Params! =NULL) { the for(inti = 0; i < params.length; i++) {BayiPstmt.setobject (i + 1), Params[i]); the } the } -num =pstmt.executeupdate (); - the returnnum; the } the the /** - * Close Database connection the * @paramConn Database Connection the * @parampstmt Statement Object the * @paramRs ResultSet Object94 */ the protected voidCloseAll (Connection conn, PreparedStatement pstmt, ResultSet rs) { the Try { the if(rs! =NULL) {98 rs.close (); About } - if(Pstmt! =NULL) {101 pstmt.close ();102 }103 if(Conn! =NULL) {104 conn.close (); the }106}Catch(SQLException e) {107 e.printstacktrace ();108 }109 } the}
Database manipulation of DAO in DAO mode in Java (Basedao notation)