当前位置:网站首页>JDBC事务提交事例

JDBC事务提交事例

2022-06-27 06:55:00 青云ing

import com.mysql.jdbc.Driver;

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

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

        //1 获取连接
        String url = "jdbc:mysql://IP:Port/db_name";
        String username = "username ";
        String password = "password ";
        Connection conn = DriverManager.getConnection(url, username, password);

        //2 sql 语句
        String sql = "update account set age=18 where id=1";
        //3 获取执行sql的对象
        Statement stmt = conn.createStatement();

        try {
            //开启事务
            conn.setAutoCommit(false);
            //4 执行sql
            int count = stmt.executeUpdate(sql);
            //5 打印处理结果
            System.out.println(count);
            //提交事务
            conn.commit();

        } catch (Exception e) {
            conn.rollback();
            e.printStackTrace();

        }
        //6 释放资源
        stmt.close();
        conn.close();
    }
}

原网站

版权声明
本文为[青云ing]所创,转载请带上原文链接,感谢
https://blog.csdn.net/shuikanshui/article/details/125413226