1、封装
package com.glutnn.test;import java.sql.*;public class DBUtil { /** * 工具类中的构造方法是私有的 * 因为工具类中的方法都是静态的,不需要new对象,直接采用类名调用即可 */ private DBUtil(){} /** * 静态代码块在类加载的时刻执行,并且只执行一次 */ static{ try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 获取数据库连接对象 * @return 连接对象 * @throws SQLException */ public static Connection getConnection() throws SQLException { return DriverManager.getConnection("jdbc:mysql://localhost:3306/bjprowernode","root","2000"); } /** * 释放资源 * @param conn 连接对象 * @param ps 数据库操作对象 * @param rs 结果集 */ public static void close(Connection conn , Statement ps , ResultSet rs){ if (rs != null) { try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (ps != null) { try { ps.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } }}
2、测试,模糊查询
package com.glutnn.test;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;/** * 测试DBUtil * 写一个模糊查询 */public class JDBCTest05 { public static void main(String[] args) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { //获取连接 conn = DBUtil.getConnection(); //获取预编译的数据库操作对象 String sql = "select ename from emp where ename like ?"; ps = conn.prepareStatement(sql); ps.setString(1,"_A%"); rs = ps.executeQuery(); while (rs.next()){ System.out.println(rs.getString("ename")); } } catch (SQLException throwables) { throwables.printStackTrace(); } finally { //释放资源 DBUtil.close(conn,ps,rs); } }}
3、悲观锁和乐观锁
