封装工具类
为了减少代码工作量,将JDBC注册、获取连接、释放连接封装为一个工具类;
具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| public class JDBCUtils { private static String url; private static String user; private static String password; private static String driver; static{ try { Properties pro = new Properties(); ClassLoader classLoader = JDBCUtils.class.getClassLoader(); URL res = classLoader.getResource("jdbc.properties"); String path = res.getPath(); System.out.println(path); pro.load(new FileReader(path));
url = pro.getProperty("url"); user = pro.getProperty("user"); password = pro.getProperty("password"); driver = pro.getProperty("driver"); Class.forName(driver); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url,user,password); } 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(); } } } 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(); } } } }
|
src 下 jdbc.properties 内容如下:
1 2 3 4
| url=jdbc:mysql: user=root password=root driver=com.mysql.cj.jdbc.Driver
|
如果你数据库连接默认为 locahost:3306 则可以简写为///+数据库名称,?serverTimezone=UTC 是为了避免时区不同问题;
调用工具类
调用工具类具体实例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| public class JDBCdemo08 {
public static void main(String[] args) { List<Emp> list = new JDBCdemo08().findAll(); System.out.println(list); System.out.println(list.size()); } public List<Emp> findAll(){ Connection conn = null; Statement stmt = null; ResultSet rs = null; List<Emp> list = null; try { conn = JDBCUtils.getConnection(); String sql = "select *from admin"; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); Emp emp = null; list = new ArrayList<Emp>(); while(rs.next()){ int id = rs.getInt("aid"); String name = rs.getString("aname"); int password = rs.getInt("apassword"); String sex = rs.getString("asex"); int age = rs.getInt("aage"); emp = new Emp(); emp.setId(id); emp.setName(name); emp.setSex(sex); emp.setPassword(password); list.add(emp); } } catch (SQLException e) { e.printStackTrace(); }finally { JDBCUtils.close(rs,stmt,conn); } return list; }
}
|