javaweb--JDBC的API-Connection

发布时间 2023-10-28 16:30:52作者: na2co3-

1、获取执行SQL对象

2、管理事务

setAutoCommit(bool) true为自动提交false为手动提交

commit()提交事务

rollback()回滚事务

package com.avb.jdbc;

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

public class jdbcdemo {
    public static void main(String[] args) throws Exception {
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");
        //获取连接
        String url = "jdbc:mysql://127.0.0.1:3306/db1";
        String username = "root";
        String password = "root";
        Connection conn = DriverManager.getConnection(url,username,password);

        //定义sql
        String sql1 = "update account set money = 2000 where id = 1";
        String sql2 = "update account set money = 1000 where id = 2";

        //获取执行sql的对象Statement
        Statement stmt = conn.createStatement();
        //执行sql
    
        try {
            //建立事务
            conn.setAutoCommit(false);
            int count1 = stmt.executeUpdate(sql1);
            int a = 3/0;
            int count2 = stmt.executeUpdate(sql2);
            //事务提交
            conn.commit();
        } catch (Exception throwables) {
            throwables.printStackTrace();
            //事务会滚
            conn.rollback();
        }
        //释放资源
        stmt.close();
        conn.close();
    }
}