In the past, when writing code, everything involved database connections, especially the DAO layer in the project. Every time I wrote a method, I had to repeat the steps: load the database driver, establish a connection... This made the code very cumbersome and time-consuming, so I thought about it today. After thinking about it, I wrote a tool class to connect to the database for later use. After testing, the function can be realized, and each method can be run.
code show as below
import java.sql.*; /** * @Description connection database tool class * @Author single continuation * @Date 2016/10/26 14:50 */ public class DBConn { private String DRIVER = "com.mysql.jdbc.Driver"; private String USERNAME = "root"; private String PASSWORD = "root"; private String URL = "jdbc:mysql://localhost:3306/"; private Connection conn = null; private PreparedStatement ps = null; private ResultSet rs = null; /** * Step 1: Load the database driver * Step 2: Establish a database connection * @param dbName database name */ public DBConn(String dbName){ try { Class.forName(DRIVER); URL = URL + dbName; conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); } catch (ClassNotFoundException e) { e.printStackTrace (); } catch (SQLException e) { e.printStackTrace (); } } /** * Step 3: write sql statement * Step 4: Create the sql statement executor preparedStatement * @param sql sql statement */ public void preparedStatement(String sql){ try { ps = conn.prepareStatement(sql); } catch (SQLException e) { e.printStackTrace (); } } /** * Step 5: Replace the placeholders with parameters * @param index placeholder index (first one is 1) * @param value parameter value */ public void setString(int index,String value){ try { ps.setString(index,value); } catch (SQLException e) { e.printStackTrace (); } } public void setInt(int index,int value){ try { ps.setInt(index,value); } catch (SQLException e) { e.printStackTrace (); } } /** * Step 6: Execute the sql statement and return the number of affected rows * @return the number of rows affected by executing the sql statement */ public int executeUpdate(){ try { //System.out.println(ps); return ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace (); } return 0; } /** * Step 6: Execute the sql statement and return the result set * @return ResultSet */ public ResultSet executeQuery(){ try { return ps.executeQuery(); } catch (SQLException e) { e.printStackTrace (); } return null; } /** * close the connection and others */ public void close(){ try{ if(rs != null){ rs.close(); } if(ps != null){ ps.close(); } if(conn != null){ conn.close(); } } catch (SQLException e) { e.printStackTrace (); } } }
When in use, instantiate this class, and the constructor will pass in the database name as a parameter to form a link.