---
title: "java 数据库操作，事务回滚"
author: "yaoweinan"
date: "2011-05-10T16:11:51Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2012-06-04T23:52:20Z"
id: 1039167
url: "https://ilyon.iteye.com/blog/1039167"
---

```
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**




*java 事务回滚操作
*
**/
public class TestTransaction {
	public static void main(String[] args) {
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		PreparedStatement ps = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/mydb", "root", "root");
			System.out.println("数据库已连接!");
			stmt = con.createStatement();
			修改默认的自动提交数据，执行多条数据
			con.setAutoCommit(false);
			stmt.addBatch(sql);
			stmt.addBatch(sql1);
			stmt.executeBatch();// 提交事务
			con.commit();
			con.setAutoCommit(true);// 恢复默认							} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException se) {
			se.printStackTrace();
			try {
					if (con != null) {
					con.rollback();//出现sql异常，事务回滚
					con.setAutoCommit(true);//设置提交方式为默认方式				}
			} catch (SQLException se1) {
				se.printStackTrace();
			}
		} finally {
			try {
				if (rs != null) {
					rs.close();
					rs = null;
				}
				if (stmt != null) {
					stmt.close();
					stmt = null;
				}
				if (con != null) {
					con.close();
					con = null;
				}
			} catch (SQLException se) {
				se.printStackTrace();
			}
		}
	}

}
```