JDBC-API详解-Connection

发布时间 2023-06-14 21:00:43作者: Karlshell
package Test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCdemo2_connection {
    public static void main(String[] args) throws Exception {
        //1.注册驱动
        //Class.forName("com.mysql.jdbc.Driver");
        //2.获取连接
        String url ="jdbc:mysql:///test?useSSL=false";
        String username="root";
        String password="1234";
        Connection conn = DriverManager.getConnection(url, username, password);
        //3.定义sql
        String sql1="update test set money = 3000 where id=1";
        String sql2="update test set money = 3000 where id=2";
        //4.获取执行sql的对象Statement
        Statement stmt = conn.createStatement();
        try {
            //开启事务
            conn.setAutoCommit(false);

            //5.执行sql1
            int count1 = stmt.executeUpdate(sql1);//返回受影响的行数
            //6.处理结果
            System.out.println(count1);
            //5.执行sql2
            int count2 = stmt.executeUpdate(sql2);//返回受影响的行数
            //6.处理结果
            System.out.println(count2);

            //提交事务
            conn.commit();
        } catch (SQLException e) {
            //回滚事务
            conn.rollback();
            throw new RuntimeException(e);
        }
        //7.释放资源
        conn.close();
        stmt.close();
    }
}