小知识1:此处的感叹号是软件提醒你声明了但没有使用,占用资源。
小知识2:对比spring事务的自动处理模式:
package demo_jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; //jdbc的直连 public class conectionPool { //四个属性 private static final String URL="jdbc:mysql://localhost:3306/cc_student?useUnicode=true&characterEncoding=utf8"; private static final String USER="root"; private static final String PASSWORD="3306"; private static final String DRIVER="com.mysql.jdbc.Driver";//驱动 //连接 public static Connection getConnection(){ try { System.out.println("程序加载成功"); //加载驱动 Class.forName(DRIVER); Connection connection = DriverManager.getConnection(URL, USER, PASSWORD); return connection; } catch (Exception e) {//改成基类的 e.printStackTrace(); System.out.println("程序加载失败"); return null; } } public static void main(String[] args) { //getConnection(); //findAll(); save(); } //简单查询 public static void findAll(){ String sql="select * from stu"; //创建数据库的连接 //先都null防止报错 Connection connection = null; Statement stat = null; ResultSet rs = null;//接收 try { connection = conectionPool.getConnection(); stat = connection.createStatement(); rs = stat.executeQuery(sql); while(rs.next()){ System.out.println(rs.getInt("no")); System.out.print(" "+rs.getString("name")); System.out.print(" "+rs.getString("sex")); System.out.print(" "+rs.getInt("age")); System.out.print(" "+rs.getString("notes")); } } catch (SQLException e) { e.printStackTrace(); }finally { //后开先关 try { rs.close(); stat.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } //简单增加 public static void save(){ String sql = "insert into stu(no,name,sex,age,notes) values(0,'星星','女',18,'备注')"; //创建数据库的连接 Connection connection = null; Statement stat = null; try { //1.开启连接 connection = conectionPool.getConnection(); //2.开启事务管理 connection.setAutoCommit(false);//默认true自动提交模式,开启事务管理的一部分,false指手动提交模式 //3.执行业务代码 stat = connection.createStatement(); stat.executeUpdate(sql); //4.若有2是false,才需要4:提交事务;若2是自动提交则无需4,否则报错。 connection.commit(); //对比spring事务,自动处理模式,针对2、4 } catch (SQLException e) { //4.事物的回滚,无论哪里出现问题需要报错,都可以回滚到上一步骤,防止伤害程序 try { connection.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); }finally { //后开先关 try { //5.关闭连接和业务应用 stat.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)