127.JDBC API
128.JDBC-Utils
public class JDBCUtils { //这是一个工具类,完成mysql的连接和关闭资源 //顶柜相关的属性(4个),因为只需要一份,因此做成static private static String user;//用户名 private static String password;//密码 private static String url;//url private static String driver;//驱动名 //在static代码块去初始化 static { try{ Properties properties = new Properties(); properties.load(new FileInputStream("src\\mysql.properties")); //读取相关的属性值 user = properties.getProperty("user"); password = properties.getProperty("password"); url = properties.getProperty("url"); driver = properties.getProperty("driver"); } catch (IOException e) { //在实际开发中,可以如下处理 //1.将编译异常转成 运行异常 //2.这时调用者可以选择捕获该异常 或 默认处理,比较方便 throw new RuntimeException(e); } } //连接数据库,返回Connection public static Connection getConnection() { try{ return DriverManager.getConnection(url,user,password); } catch (SQLException e) { throw new RuntimeException(e); } } //关闭相关资源 /* 1.Result 结果集 2.Statement 或者 PreparedStatement 3.Connection 4.如果需要关闭资源,就传入对象,否则传入空 */ public static void close(ResultSet set, Statement statement,Connection connection) { //判断是否为null try{ if (set != null) { set.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { throw new RuntimeException(e); } } }
测试JDBC-Utils工具类,完成dml语句
public class TestJava { //演示如果使用JDBCUtils工具类,完成dml 和 select public void testDML() {//insert , update , delete //1.得到链接 Connection connection = null; //2.组织一个sql String sql = "update actor set name = ? where id = ?"; PreparedStatement preparedStatement = null; //3.创建PreparedStatement 对象 try { connection = JDBCUtils.getConnection(); preparedStatement = connection.prepareStatement(sql); //给占位符赋值 preparedStatement.setString(1,"周星驰"); preparedStatement.setInt(2,4); //执行 preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { //关闭资源 JDBCUtils.close(null,preparedStatement,connection); } } }