package cn.xiaohei.insert; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class TestInsert2 { public static void main(String[] args) { //声明jdbc变量 Connection conn = null; Statement stmt = null; //声明jdbc参数 String driver = "oracle.jdbc.driver.OracleDriver"; String url = "jdbc:oracle:thin:@127.0.0.1:1521:XE"; String username = "scott"; String password = "tiger"; try { //1.加载驱动类 Class.forName(driver); //2.连接指定的数据库对象 conn = DriverManager.getConnection(url,username,password); //3.设置自动提交设置为false conn.setAutoCommit(false); //3.获取sql命令对象 stmt = conn.createStatement(); //4.创建SQL命令 String sql = "insert into dept values(80,'吃鸡学院','北京')"; String sql2 = "select * from emp"; //5.执行SQL命令 int i = stmt.executeUpdate(sql2);//返回-1表示失败,返回其它数表示成功执行的条数。 System.out.println("执行结果:"+i); conn.commit(); } catch (ClassNotFoundException e) { e.printStackTrace(); }catch(SQLException e){ try { conn.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); }finally { //6.关闭流 try { if(stmt!=null) { stmt.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if(conn!=null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } }
值得注意的地方:Oracle删除delete数据如果数据不存在,不会报错,所以返回的i为0而不是-1