JDBC Implements bank transfer transactions

Source: Internet
Author: User
Tags rollback
Import java.sql.*;
	public class Testdemo {private static String Driver = "Com.mysql.jdbc.Driver";
	private static String URL = "Jdbc:mysql:///test";
	private static String user = "root";

	private static String password = "";
		/** * method to connect to the database */public static Connection Getcon () throws Exception {Class.forName (driver);
		Connection con = drivermanager.getconnection (url, user, password);
	return con; 
		}/** * method to close the database */public static void close (Connection con, preparedstatement PS, ResultSet rs) throws Exception {
		if (rs! = null) rs.close ();
		if (PS! = null) ps.close ();
	if (con! = null) con.close (); }/** * Test */@SuppressWarnings ("unused") public static void main (string[] args) throws Exception {Connection C
		on = null;
		PreparedStatement PS1 = null;
		PreparedStatement PS2 = null;
		String sql = "Update bank set money=money-500 where userid=1";
		String sql2 = "Update bank set money=money+500 where userid=2";
			try {con = Getcon (); COn.setautocommit (FALSE);
			PS1 = con.preparestatement (sql);
			int result1 = Ps1.executeupdate ();
			PS2 = Con.preparestatement (SQL2);
			int result2 = Ps2.executeupdate ();
			if (false) throw new RuntimeException ("Analog exception"); if (result1 = = 1 && result2 = = 1) {System.out.println ("Transfer succeeded.
				");
			Con.commit (); } else {System.out.println ("The transfer failed, has been rolled back.
				");
			Con.rollback ();
			}} catch (Exception e) {e.printstacktrace ();
			Con.rollback (); System.out.println ("The transfer failed and has been rolled back.
		");
			} finally {close (con, PS1, null);
		Close (con, PS2, null);
 }
	}
}

DROP TABLE IF EXISTS Bank;
The CREATE TABLE Bank (id int (one) is not NULL, UserID int (one) is not NULL, and money varchar is not NULL, PRIMARY KEY (id));
INSERT into bank VALUES (1, 1, ' 10000 '), (2, 2, ' 10000 ');


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.