Database Operation Template Method

Source: Internet
Author: User

[Java] jdbc. properties url = jdbc: mysql: // localhost: 3306/cfms user = root password = 123456 driverClass = com. mysql. jdbc. driver package cn.edu. hactcm. base. utils; import java. io. inputStream; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. resultSet; import java. SQL. SQLException; import java. SQL. statement; import java. util. properties;/** [java] view plaincopyprint? * CFMS: Computer files management system * version: 1.0 08:44:27 ** tool class for JDBC operations */public class JdbcUtils {private JdbcUtils () {} private static String url; private static String user; private static String password;/** static code block */static {try {// read the configuration file, read the attribute file InputStream in = JdbcUtils by using the class loader. class. getClassLoader (). getResourceAsStream ("jdbc. properties "); Properties prop = new P Roperties (); prop. load (in); url = prop. getProperty ("url"); user = prop. getProperty ("user"); password = prop. getProperty ("password"); // register the driver String driverClass = prop. getProperty ("driverClass"); Class. forName (driverClass); in. close (); in = null;} catch (Exception e) {throw new ExceptionInInitializerError (e );}} /*** @ return gets the Connection to the specified database * @ throws SQLException */public static Connection getConn Ection () throws SQLException {// url, user, password can be directly used because it is defined as static. Connection connection = DriverManager. getConnection (url, user, password); return connection;}/*** @ param rs: result set * @ param stmt: PrepareStatement is used in the program, where Statement is its parent class * @ param conn: database Connection */public static void release (ResultSet rs, Statement stmt, Connection conn) {// determines whether the result set is empty, if not empty, disable if (rs! = Null) {try {rs. close ();} catch (SQLException e) {e. printStackTrace () ;}rs = null;} // determines whether the declaration is null. if not, disable if (stmt! = Null) {try {stmt. close ();} catch (SQLException e) {e. printStackTrace () ;}stmt = null;} // determines whether the connection is null. if not, disable if (conn! = Null) {try {conn. close ();} catch (SQLException e) {e. printStackTrace () ;}conn = null ;}} package cn.edu. hactcm. base. dao; import java. SQL. resultSet;/*** CFMS: Computer files management system * version: 1.0 10:02:31 */public interface ResultSetHandler {// method for processing the result set public Object handle (ResultSet rs);}/*****/package cn.edu. hactcm. base. dao. impl; import java. SQL. resultSet; I Mport java. SQL. resultSetMetaData; import cn.edu. hactcm. base. dao. resultSetHandler;/*** CFMS: Computer files management system * version: 1.0 10:38:37 ** save all records in the first row to an Object array */@ SuppressWarnings ({"unchecked", "unused "}) public class ArrayHandler implements ResultSetHandler {private Class clazz; public ArrayHandler (Class clazz) {this. clazz = clazz;} public Object handle (Result Set rs) {try {if (rs. next () {// point to the record of the first row // obtain the metaData ResultSetMetaData metaData = rs. getMetaData (); // obtain the number of Field columns in the SQL statement used for query. int count = metaData. getColumnCount (); // create an array Object [] arr = new Object [count]; // iterate the values of all columns and save them to the array for (int I = 1; I <= count; I ++) {Object value = rs. getObject (I); // get the value of the specified column arr [I-1] = value;} return arr;} return null;} catch (Exception e) {throw new RuntimeException (e ); }}}/*****/Package cn.edu. hactcm. base. dao. impl; import java. lang. reflect. field; import java. SQL. resultSet; import java. SQL. resultSetMetaData; import cn.edu. hactcm. base. dao. resultSetHandler;/*** CFMS: Computer files management system * version: 1.0 10:38:37 ** This helper class is used to obtain the first record in the result set */@ SuppressWarnings ("unchecked ") public class BeanHandler implements ResultSetHandler {private Clas S clazz; public BeanHandler (Class clazz) {this. clazz = clazz;} public Object handle (ResultSet rs) {// I do not know how many columns of data exist. I do not know the column name, I do not know what bean // table columns are encapsulated into. The field names of the javabean are the same. try {if (rs. next () {// create bean Object bean = clazz. newInstance (); // encapsulate data // obtain the result set metaData ResultSetMetaData metaData = rs. getMetaData (); int count = metaData. getColumnCount (); // iterator the data of each column for (int I = 1; I <= count; I ++) {// obtain the column name username String c OlumnName = metaData. getColumnName (I); // get the data ddd Object value = rs. getObject (columnName); // The ing property username Field = clazz is reflected Based on the column name. getDeclaredField (columnName); // assign field to the attribute. setAccessible (true); field. set (bean, value);} return bean;} return null;} catch (Exception e) {throw new RuntimeException (e) ;}} package cn.edu. hactcm. base. dao. impl; import java. lang. reflect. field; import java. s Ql. resultSet; import java. SQL. resultSetMetaData; import java. util. arrayList; import java. util. list; import cn.edu. hactcm. base. dao. resultSetHandler;/*** CFMS: Computer files management system * version: 1.0 10:07:19 ** This helper class is used to obtain a list set of records in the result set, each element in the set is a record in the database */@ SuppressWarnings ("unchecked") public class BeanListHandler implements ResultSetHandler {private Class clazz; public Be AnListHandler (Class clazz) {this. clazz = clazz;} public Object handle (ResultSet rs) {try {// retrieve all records in the result set, encapsulate them into beans, and store them in the list to return List = new ArrayList (); while (rs. next () {Object bean = clazz. newInstance (); // obtain the metaData ResultSetMetaData metaData = rs. getMetaData (); // get the number of columns int count = metaData. getColumnCount (); // traverse the column for (int I = 1; I <= count; I ++) {// retrieve the column name String columnName = metaData. getColum NName (I); // obtain the value of this column Object value = rs. getObject (columnName); // returns the attribute Field = clazz. getDeclaredField (columnName); // you can specify the attribute field. setAccessible (true); field. set (bean, value);} // Add to list. add (bean) ;}return list ;}catch (Exception e) {throw new RuntimeException (e) ;}} package cn.edu. hactcm. base. dao. impl; import java. SQL. connection; import java. SQL. preparedStatement; import java. SQL. re SultSet; import java. SQL. SQLException; import cn.edu. hactcm. base. dao. resultSetHandler; import cn.edu. hactcm. base. utils. jdbcUtils; public class GenericDaoImpl {/*** is used to process common insert, update, and delete operations * @ param SQL: Here is the input SQL statement * @ param params: here is the parameter array * @ return * @ throws SQLException */public static int update (String SQL, Object [] params) throws SQLException {Connection conn = null; PreparedStatement Pstmt = null; ResultSet rs = null; try {conn = JdbcUtils. getConnection (); // pre-compiled SQL pstmt = conn. prepareStatement (SQL); // set the parameter to for (int I = 0; I <params. length; I ++) {pstmt. setObject (I + 1, params [I]);} // send SQL int num = pstmt.exe cuteUpdate (); return num;} finally {JdbcUtils. release (rs, pstmt, conn) ;}/ *** used to process public "query all" operations * @ param SQL: query parameter * @ param params: id value * @ param rsh: indicates the end to be implemented Result encapsulation class * @ return * @ throws SQLException */public static Object query (String SQL, Object [] params, ResultSetHandler rsh) throws SQLException {Connection conn = null; preparedStatement pstmt = null; ResultSet rs = null; try {// get connection conn = JdbcUtils. getConnection (); // pre-compiled SQL pstmt = conn. prepareStatement (SQL); // set the parameter to for (int I = 0; params! = Null & I <params. length; I ++) {pstmt. setObject (I + 1, params [I]);} // send SQL rs = pstmt.exe cuteQuery (); // do not know how others want to process the result set // simply think about the processor of another result set // define a result set Processor interface // policy mode for the current code to continue, specifies the algorithm. The specific algorithm is left to future callers to implement Object obj = rsh. handle (rs); return obj;} finally {// release resources JdbcUtils. release (rs, pstmt, conn );}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.