connection&statement

//获取连接
     String url = "jdbc:mysql:///xuexi";
     String user = "root";
     String passwd = "123321";
     Connection connection = DriverManager.getConnection(url,user,passwd);
     Statement statement = connection.createStatement();     //获取连接对象
     String sql = "UPDATE ck set ck = ck - 500 WHERE ename = '张三'";
     try {
         connection.setAutoCommit(false);   //修改手动提交
         statement.executeUpdate(sql);
         connection.commit();   //没出问题执行成功
         System.out.println("执行sql语句成功");
     }catch (Exception a){
         connection.rollback();  //执行失败报错了回滚事务
         System.out.println("执行失败");
     }

public static void main(String[] args) throws Exception {

       textDML();
   }
   public static void textDML() throws Exception{
       String url = "jdbc:mysql:///xuexi";
       String user  = "root";
       String passwd = "123321";
       Connection connection = DriverManager.getConnection(url, user, passwd);
       String sql = "CREATe TABLE yyg(\n" +
               "id int PRIMARY key auto_increment,\n" +
               "ename VARCHAR(30),\n" +
               "sex VARCHAR(1),\n" +
               "rq date NOT NULL,\n" +
               "bm INT\n" +
               ")";
       Statement statement = connection.createStatement();
       try {
           connection.setAutoCommit(false);
           statement.executeUpdate(sql);
           System.out.println("执行成功");
           connection.commit();
       }catch (Exception a){
           System.out.println("执行失败");
       }

   }

您可能还喜欢...