We found a high degree of code repetition here  

## extract JDBC Tool class : JDBCUtils
    * objective : Simplified writing
    * analysis :
        1. Registered drivers are also extracted
        2. Extract a method to get the connection object
// return
DriverManager.getConnection("jdbc:mysql:///db3","root","root"); Or define methods to pass parameters
If it is written in this way, the generality is not good and the code is complex
            * demand : Do not want to pass parameters ( trouble ), We must also ensure the universality of tool classes .
            * solve : configuration file
                jdbc.properties
                    url=
                    user=
                    password=
        3. Extract a method to release resources

jdbcutils: jdbc Tool class
package cn.itcast.utils; import java.io.FileReader; import
java.io.IOException; import java.io.InputStream; import java.net.URL; import
java.sql.*; import java.util.Properties; /* Jdbc Tool class */ public class JdbcUtils {
private static String url; // Promote the scope of these three variables that are originally local variables private static String user;
private static String password; private static String driver; // Why is this a static member variable
Because only static member variables and member methods can be accessed by static code segments /*
File reading , You only need to read these values once "jdbc:mysql:///db3","root","root" Using static code blocks */ static
{// Static code block try { // Read resource file Get value Get the value to getConnection() Method use //1. establish Properties Collection class
Properties pro = new Properties(); //2. load file //pro.load(new
FileReader("src/jdbc.properties")); // Error reported here before Solution 1: write the absolute address above the address //
The second method is acquisition src How to file under path --》ClassLoader Class loader ClassLoader classLoader =
JdbcUtils.class.getClassLoader(); //classloader Class loader URL res =
classLoader.getResource("jdbc.properties"); // Returned Url Is a uniform resource locator You can locate the absolute path of a file
String path = res.getPath(); // use getPath(); Method to get the absolute path sure sout Look at the path What you get is the absolute path
pro.load(new FileReader(path)); //3. Get attribute assignment url = pro.getProperty("url"); user =
pro.getProperty("user"); password = pro.getProperty("password"); driver =
pro.getProperty("driver"); //4. Register driver Class.forName(driver); } catch (IOException
e) { e.printStackTrace(); } catch (ClassNotFoundException e) {
e.printStackTrace(); } } // Method of obtaining connection public static Connection getConnection()
throws SQLException { // Member method The return value is a Connection Type of data // Method of obtaining connection The connection object is returned //
A feature of tool classes is that all methods are static and easy to call So here's a static method plus static return
DriverManager.getConnection("url,user,password"); } // Methods of releasing resources /** * Define how to free resources *
Use addition, deletion and modification to release connection and statement object * When using a query, you also need to release one ResultSet object * So here are two actions Use overloaded mechanism
*/ public static void close(Statement stmt, Connection conn) { if (stmt !=
null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } }
if (conn != null) { try { conn.close(); } catch (SQLException e) {
e.printStackTrace(); } } } /** * heavy load close method */ public static void
close(ResultSet rs, Statement stmt, Connection conn) { if (rs != null) { try {
rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt !=
null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } }
if (conn != null) { try { conn.close(); } catch (SQLException e) {
e.printStackTrace(); } } } }
configuration file jdbc.properties

\

  Test class
package cn.itcast.jdbc; import cn.itcast.domain.Emp; import
cn.itcast.utils.JdbcUtils; import java.sql.*; import java.util.ArrayList;
import java.util.List; /* demand : demonstration jdbcutils Tool class */ public class JdbcDemo09 { public
static void main(String[] args) { List<Emp> list = new
JdbcDemo09().findAll02(); System.out.println(list); } /* Query all Emp object */ public
List<Emp> findAll02() { // Here is a method defined //1.jdbc Query steps for //1. Register driver Connection conn =
null; // Extracted and directly referenced below ResultSet rs = null; Statement stmt = null; List<Emp>
list=null; try { /* Class.forName("com.mysql.jdbc.Driver"); //3. Get connection conn =
DriverManager.getConnection("jdbc:mysql:///db3", "root", "root");*/ conn=
JdbcUtils.getConnection(); //jdbc Tool class one sentence And if you change the content, you can change it directly in the configuration file //sql sentence String sql =
"select*from emp"; stmt = conn.createStatement(); // implement sql
Query method .executeQuery(sql); rs = stmt.executeQuery(sql); // Traversal result set , Encapsulated object , Mount collection Emp
emp = null; // Here is create emp quote It can be reused directly later list = new ArrayList<>(); while (rs.next()) {
// get data int id = rs.getInt("id"); String ename = rs.getString("ename"); int
job_id = rs.getInt("job_id"); int mgr = rs.getInt("mgr"); Date joindate =
rs.getDate("joindate"); double salary = rs.getDouble("salary"); double bonus =
rs.getDouble("bonus"); int dept_id = rs.getInt("dept_id"); // establish emp object emp = new
Emp(); // Note that this is not Emp emp = new Emp(); Here is a kind of reuse emp.setId(id); // Here is Emp In class geter
seter Methods are working emp.setEname(ename); emp.setJob_id(job_id); emp.setMgr(mgr);
emp.setJoindate(joindate); emp.setSalary(salary); emp.setBouns(bonus);
emp.setDept_id(dept_id); // These are all in the class set Method plus data // Mount collection list.add(emp); // There is one in the collection emp class }
} catch (SQLException ex) { ex.printStackTrace(); } /*finally{ if (rs!=null){
try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } }
if(stmt!=null){ try { stmt.close(); } catch (SQLException e) {
e.printStackTrace(); } } if (conn!=null){ try { conn.close(); } catch
(SQLException e) { e.printStackTrace(); } } }*/ JdbcUtils.close(rs,stmt,conn);
// use jdbc Methods in tool classes return list ; } }

Technology
©2019-2020 Toolsou All rights reserved,
Redis Underlying data structure A person who dissuades others from learning computer , Are not good people win10 System computer C Where's the disc ,c disc users where? (win10c Disk not found users) Freshman c Language student management system ( lower ) hospital WIFI Which family is strong ? utilize Python Script unlimited spoof girlfriend computer C language program design —— Student management system Byte runout - Test development practice - One side cool meridian python Run code at specified time 5 Best style Linux Server system recommendation Anti anxiety life after naked resignation , I believe everything will have the best arrangement