Java Summary (essay)--code summary JDBC and transaction, take bank transfer, audit, etc. for example

Source: Internet
Author: User
Tags readline

This article is a functional extension of the example of a transaction in the previous article to deepen understanding and code proficiency:
(1) Database tables

Data:

(2) Introduction of database connection Jar Package
(3) Tool type:

Package Org.jdbc.util;import Java.io.file;import Java.io.fileinputstream;import java.io.inputstream;import Java.sql.connection;import Java.sql.drivermanager;import Java.sql.resultset;import Java.sql.SQLException;import    Java.sql.statement;import java.util.properties;//Operation Database Tool class public class Dbutil {//Privatization construction Method Private Dbutil () {}    private static String URL = null;    private static String user = null;    private static String password = NULL;            static {try {Class.forName ("com.mysql.jdbc.Driver");            Properties Pro = new properties ();            Pro.load (New FileInputStream ("Src/jdbc.properties"));            url = pro.getproperty ("url");            user = Pro.getproperty ("user");        Password = pro.getproperty ("password");        } catch (Exception e) {e.printstacktrace (); }}//Read external properties file to get Connection object, manually enter URL public static Connection getConnection1 (String URL) {Properties pro = new        Properties (); ConnectiOn conn = null;        InputStream input = null;            try {input = new FileInputStream ("E:" + file.separator + "jdbc.properties");            Pro.load (input);        conn = drivermanager.getconnection (URL, pro);        } catch (Exception e) {e.printstacktrace ();    } return conn;  }//Read the configuration file under the project, get the Connection object parameters, do not need to manually enter the URL public static Connection GetConnection2 () throws SQLException {Connection        conn = drivermanager.getconnection (URL, user, password);    Return conn; }//Release all resources public static void CloseAll (Connection conn, Statement Stat, ResultSet rs) throws Sqlexceptio        n {if (conn! = null) {conn.close ();        } if (stat! = null) {stat.close ();        } if (rs! = null) {rs.close ();        }}//Release the resource used public static void Closepart (Connection conn, Statement Stat) throws SQLException {      IF (conn! = null) {      Conn.close ();        } if (stat! = null) {stat.close (); }    }}

(4) Writing code:

Package Org.jdbc.transcation;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.sql.connection;import Java.sql.preparedstatement;import Java.sql.ResultSet; Import Java.sql.sqlexception;import Java.util.scanner;import Org.jdbc.util.dbutil;public class AccountDemo {//Main method control operation Row direction public static void main (string[] args) {BufferedReader br = new BufferedReader (New InputStreamReader (System        . in));        Scanner scan = new Scanner (system.in);        System.out.println ("Welcome to the analog banking interface");            while (true) {System.out.print ("Please enter your choice (1 Transfer 2 Enquiry 3 Deposit 4 Withdrawals 5 account opening 8 exit):");            int chioce;                try {chioce = Scan.nextint ();                    if (Chioce = = 1 | chioce = = 2 | chioce = 3 | chioce==4 | chioce==5 |CHIOCE = 8) {switch (CHIOCE) {                        Case 1://Transfer System.out.print ("Please enter the name of the transfer account:");    String fromname = Br.readline ();                    System.out.print ("Please enter the account name:");                        String toname = Br.readline ();                        System.out.print ("Please enter the transfer amount:");                        int money = Scan.nextint ();                        Boolean flag = TransferMoney (FromName, ToName, money);                            if (flag) {System.out.println ("successful transfer");                            Showbalance (ToName);                        Showbalance (FromName); } else {System.out.println ("Please check that you entered the correct information, please enter the correct information, re-handle this business, thank you!")                        ");                    } break;                        Case 2://Query System.out.print ("Please select (1: Check all account information \t2: Personal account Information):");                        int chioce1 = Scan.nextint (); if (Chioce1 = = 1 | chioce1 = = 2) {switch (CHIOCE1) {Case 1://Query full  Department account SelectAll ();                              Break                                Case 2://Enquiry for Personal account System.out.print ("Please enter enquiry account name:");                                String balname = Br.readline ();                                Selectpart (Balname);                            Break                        }} else {System.out.println ("Your options are wrong, please re-enter");                    } break;                        Case 3://Deposit System.out.print ("Please enter deposit account name:");                        String savname = Br.readline ();                        System.out.print ("Please enter Deposit Amount:");                        int Savmoney = Scan.nextint ();                        Boolean issave = Savemoney (Savname, Savmoney);                            if (issave) {System.out.println ("deposit success");                        Showbalance (Savname); } else {SystEm.out.println ("The account information you entered is incorrect, the deposit failed.");                    } break;                        Case 4://Withdrawal System.out.print ("Please enter the withdrawal account name:");                        String draname = Br.readline ();                        System.out.print ("Please enter the withdrawal amount:");                        int Dramoney = Scan.nextint ();                        Boolean isdraw = Drawmoney (Draname, Dramoney);                            if (Isdraw) {System.out.println ("withdrawal success");                        Showbalance (Draname);                        } else {System.out.println ("The account information you entered is incorrect, the withdrawal failed.");                    } break;                        Case 5://Withdrawal System.out.print ("Please Enter account name:");                        String opname = Br.readline ();                        System.out.print ("Please enter account opening deposit amount:");                        int opbalance = Scan.nextint (); Boolean isOpen =Openaccount (Opname, opbalance);                            if (IsOpen) {System.out.println ("Congratulations, successful account opening");                            System.out.println ("Current account information:");                        Selectpart (Opname);                        } else {System.out.println ("Sorry, an exception occurred, you failed to open an account.");                    } break; Case 8://Exit the system System.out.println ("Thank You for coming, goodbye!!")                        ");                    System.exit (0);                }} else {System.out.println ("Your options are wrong, please re-enter");            }} catch (IOException e) {System.out.println ("you have an illegal operation that produces an abnormal phenomenon:" +e.getmessage ());  }}}//Turn Money Method @SuppressWarnings ("resource") public static Boolean TransferMoney (String FromName, String        ToName, int money) {Boolean flag = false;        PreparedStatement PS = null; Connection conn =Null        ResultSet Rs=null;            try {conn = Dbutil.getconnection2 ();            String sql= "SELECT * from account where name=?";            Ps=conn.preparestatement (SQL);            Ps.setstring (1, fromname);            Rs=ps.executequery ();            Boolean flag1=false;            Flag1= Rs.next ();            Ps.close ();            Ps=conn.preparestatement (SQL);            Ps.setstring (1, fromname);            Rs=ps.executequery ();            Boolean flag2=false;            Flag2= Rs.next ();            Ps.close (); if ((Flag1 && flag2)!=false) {Conn.setautocommit (false);//Cancel autocommit String sql1 = "Upda Te account set balance=balance-?                where name=? "; String sql2 = "Update account set balance=balance+?"                where name=? ";                PS = conn.preparestatement (SQL1);                Ps.setint (1, money);                Ps.setstring (2, fromname);//Turn out ps.executeupdate ();  Ps.close ();              PS = conn.preparestatement (SQL2);                Ps.setint (1, money);                Ps.setstring (2, toname);//Transfer to Ps.executeupdate ();            Conn.commit ();//COMMIT TRANSACTION flag = true;            }else{System.out.println ("Sorry, the account you entered is incorrect and cannot be transferred");        }} catch (SQLException e) {e.printstacktrace ();            } finally {try {dbutil.closeall (conn, ps,rs);            } catch (SQLException e) {e.printstacktrace ();    }} return flag;        }//All account Query method information public static void SelectAll () {PreparedStatement PS = null;        Connection conn = null;        ResultSet rs = null;            try {conn = Dbutil.getconnection2 ();//Establish connection String sql = "SELECT * from Account";            PS = conn.preparestatement (SQL);            rs = Ps.executequery ();            System.out.println ("All account information query results are:"); System.out. println ("number \ t name \ t account balance");                while (Rs.next ()) {int id = rs.getint ("id");                String name = rs.getstring ("name");                int balance = Rs.getint ("balance");            System.out.println (id + "\ t" + name + "\ T" + balance);        }} catch (SQLException e) {e.printstacktrace ();            } finally {try {dbutil.closeall (conn, PS, RS);            } catch (SQLException e) {e.printstacktrace ();        }}}//Query single account information @SuppressWarnings ("resource") public static void Selectpart (String balname) {        PreparedStatement PS = null;        Connection conn = null;        ResultSet rs = null;            try {conn = Dbutil.getconnection2 ();//Establish connection String SQL3 = "SELECT * from account where name=?";            PS = conn.preparestatement (SQL3);            Ps.setstring (1, balname);            rs = Ps.executequery (); Boolean flag = Rs.neXT ();                if (flag = = True) {System.out.println (balname + "account information query result is:");                System.out.println ("the number \ t name \ t account balance");                rs = Ps.executequery ();                    while (Rs.next ()) {int id = rs.getint ("id");                    String name = rs.getstring ("name");                    int balance = Rs.getint ("balance");                System.out.println (id + "\ t" + name + "\ T" + balance);            }} else {System.out.println ("The account information you entered does not exist, please re-enter ...");        }} catch (SQLException e) {e.printstacktrace ();            } finally {try {dbutil.closeall (conn, PS, RS);            } catch (SQLException e) {e.printstacktrace (); }}}//Save method public static Boolean Savemoney (String savename, int Savmoney) {Boolean flag = False        ;        Connection conn = null;        PreparedStatement PS = null; String SQL6 = "Update account set balance=balance+?"        where name=? ";        int count = 0;            try {conn = Dbutil.getconnection2 ();            PS = conn.preparestatement (SQL6);            Ps.setint (1, Savmoney);            Ps.setstring (2, savename);            Count = Ps.executeupdate ();            if (count! = 0) {flag = true;        }} catch (SQLException e) {e.printstacktrace ();            } finally {try {Dbutil.closepart (conn, PS);            } catch (SQLException e) {e.printstacktrace ();    }} return flag;        }//Take Money method public static Boolean Drawmoney (String drawname, int Dramoney) {Boolean flag = false;        Connection conn = null;        PreparedStatement PS = null; String SQL7 = "Update account set balance=balance-?"        where name=? ";        int count = 0;            try {conn = Dbutil.getconnection2 (); PS = conn.preparestatement (SQL7);           Ps.setint (1, Dramoney);            Ps.setstring (2, drawname);            Count = Ps.executeupdate ();            if (count! = 0) {flag = true;        }} catch (SQLException e) {e.printstacktrace ();            } finally {try {Dbutil.closepart (conn, PS);            } catch (SQLException e) {e.printstacktrace ();    }} return flag;        }//Create a new account public static Boolean Openaccount (String opname, int opbalance) {Boolean flag = false;        Connection conn = null;        PreparedStatement PS = null;        String sql9 = "INSERT into account (Name,balance) VALUES (?,?)";        int count = 0;            try {conn = Dbutil.getconnection2 ();            PS = conn.preparestatement (SQL9);            Ps.setstring (1, opname);            Ps.setint (2, opbalance);            Count = Ps.executeupdate ();            if (count! = 0) {flag = true; }       } catch (SQLException e) {e.printstacktrace ();            } finally {try {Dbutil.closepart (conn, PS);            } catch (SQLException e) {e.printstacktrace ();    }} return flag; }//Show Balance Method @SuppressWarnings ("resource") public static void Showbalance (String showname) {Preparedstateme        NT PS = null;        Connection conn = null;        ResultSet rs = null; try {conn = Dbutil.getconnection2 ();//Establish connection String Sql10 = "Select Balance from account where name=            ?";            PS = conn.preparestatement (SQL10);            Ps.setstring (1, showname);                rs = Ps.executequery ();                rs = Ps.executequery ();                    while (Rs.next ()) {int shbalance = Rs.getint ("balance");                System.out.println (ShowName + "account Current balance is:" +shbalance);   }} catch (SQLException e) {e.printstacktrace ();     } finally {try {dbutil.closeall (conn, PS, RS);            } catch (SQLException e) {e.printstacktrace (); }        }    }}

Run Result:

Welcome to the Analog banking interface Please enter your choice (1 Transfer 2 Query 3 deposit 4 Withdrawals 5 open account 8 exit): 2 Please select (1: Check all account information 2: Personal account information): 1 All account information query result is: Numbered name account Balance 1 Xiang Yu 350130202     Liu Bang 200029803 li Shimin 476180004 Zhao Kuangyin 239900005 Zhu Yuanzhang 123560006 win politics 322000007 Caocao 2000000008 Sun Quan 14500000 Please enter your choice (1 transfer 2 Enquiry 3 Deposit 4 Withdrawal 5 open account 8 exit): 1 Please enter your account name: Li Shimin Please enter the username: please input the transfer amount: 3000 transfer the current balance of the account is: 200003000 Li Shimin Account current balance is: 47615000 Please enter your choice (1 rpm) Account 2 Enquiry 3 Deposit 4 Withdrawal 5 Account opening 8 exit: 1 Please enter the name of the transfer account: hehe Please enter the account name: haha Please enter the transfer amount: 20000Sorry, you entered the wrong account, can not be transferred processing please check the information you entered is correct, please enter the correct information, re-transact this business, Thank you! Please enter your choice (1 Transfer 2 Enquiry 3 Deposit 4 Withdrawals 5 open account 8 exit): 2 Please select (1: Check all account information 2: Personal account information): 2 Please enter enquiry account name: Liu Bangliubong Account information Query result is: Number name account balance 2 Liu Bang 20002980 please Enter your choice (1 Transfer 2 Query 3 deposit 4 Withdrawals 5 open account 8 exit): 2 Please select (1: Check all account information 2: Personal account information): 3 Your options are wrong, please re-enter please enter your choice (1 Transfer 2 Query 3 deposit 4 Withdrawals 5 Account 8 exit): 2 Please select (1: Check all account information 2: Personal account information): 2 Please enter the account name: haha you entered the account information does not exist, please re-enter: Please enter your choice (1 Transfer 2 Enquiry 3 Deposit 4 Withdrawals 5 open account 8 exit): 3 Please enter the deposit account name: Zhu Yuanzhang Please enter the deposit amount: 300000 deposit successful Zhu Yuanzhang account current balance is: 12656000 Please enter your choice (1 Transfer 2 Query 3 deposit 4 Take Section 5 Account opening 8 exit): 3 Please enter the deposit account name: hehe Please enter the deposit amount: 3300 The account information you entered is incorrect and the deposit failed. Please enter your choice (1 Transfer 2 Enquiry 3 Deposit 4 Withdrawals5 Account opening 8 exit): 4 Please enter the withdrawal account name: Caocao Please enter the withdrawal amount: 250 The current balance of the account is: 200002750 Please enter your choice (1 Transfer 2 Query 3 deposit 4 Withdrawals 5 open account 8 exit): 4 Please enter the withdrawal account name: haha Please enter the withdrawal amount: 200 you lose The account information entered is incorrect, the withdrawal failed. Please enter your choice (1 Transfer 2 Enquiry 3 Deposit 4 Withdrawals 5 open account 8 exit): 5 Please enter the account name: Liyuan Please enter the deposit amount: 300000000 Congratulations, the account is successful. Current account information: Liyuan account information Query result is: Numbered name account balance 9 Liyuan 300  000000 Please enter your choice (1 Transfer 2 Query 3 deposit 4 Withdrawals 5 open account 8 exit): 2 Please select (1: Check all account information 2: Personal account information): 1 All account information query result is: Number name account Balance 1 Xiang Yu 350130202 Liu Bang 200029803 Li Shimin 476150004 Zhao Kuangyin 239900005 Zhu Yuanzhang 126560006 win politics 322000007 Caocao 2000027508 Sun Quan 145000009 Liyuan 30000000 0 Please enter your choice (1 Transfer 2 Query 3 deposit 4 Withdrawals 5 open account 8 exit): 6 Your options are wrong, please re-enter please enter your choice (1 Transfer 2 Query 3 deposit 4 Withdrawals 5 account opening 8 exit): 8 Thank you for coming, goodbye!!

Java Summary (essay)--code summary JDBC and transaction, take bank transfer, audit, etc. for example

Related Article

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.