Java MySQL multiple transaction simulation based on exchange rate transfer, and storage transfer information layered completion of the DAO Layer Service layer client layer connection pool using C3P0 write into the library using Dbutils

Source: Internet
Author: User

The use of jar packages, and the division of Layers

C3p0-config.xml

<?xml version= "1.0" encoding= "UTF-8"?><c3p0-config> <!--The default configuration, if not specified, is the most common recommendation for using this configuration default configuration at the very beginning. It's okay to put it anywhere else.-<default-config> <property name= "Driverclass" >com.mysql.jdbc.Driver</property> <property name= "Jdb CUrl ">jdbc:mysql://127.0.0.1:3306/test2</property><property name= "User" >root</property> <property name= "password" >root</property> < Property Name= "Checkouttimeout" >30000</property> <property name= "Idleconnectiontestperiod" >30</ property> <property name= "initialpoolsize" >10</property> <property name= "MaxIdleTime" >3 0</property> <property name= "maxpoolsize" >100</property> <property name= "Minpoolsize" &G t;10</property> <property name= "maxstatements" >200</property> <user-overrides user= "tes T-user "> <property name=" maxpoolsize ">10</property> <property name=" Minpoolsize "&G    t;1</property> <property name= "maxstatements" >0</property> </user-overrides> </default-config> </c3p0-config>

Jdbcutils

 PackageCn.itcast.tools;Importjava.sql.Connection;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement;ImportJavax.sql.DataSource;ImportCom.mchange.v2.c3p0.ComboPooledDataSource;/*a). Private, static member variable: Combopooleddatasource and create object; Load configuration file default configuration. b). Public, static member method: publicly static DataSource Getdatasource (), this method returns the C3P0 connection pool object; c). Public, static member method: publicly static Connection getconnection (), this method returns the Connection object obtained through the C3P0 connection pool, using the local thread ThreadLocal*/ Public classJdbcutils {Private StaticCombopooleddatasource DataSource =NewCombopooleddatasource (); Private StaticThreadlocal<connection> local=NewThreadlocal<connection>();  Public StaticDataSource Getdatasource () {returnDataSource; }         Public StaticConnection getconnection () {Connection con=Local.get (); if(con==NULL) {            Try{con=datasource.getconnection ();            Local.set (con); } Catch(SQLException e) {e.printstacktrace (); } con=Local.get (); }        returncon; }         Public Static voidClose (Connection con,statement St,resultset rs) {if(rs! =NULL) {            Try{rs.close (); } Catch(SQLException e) {e.printstacktrace (); }        }        if(St! =NULL) {            Try{st.close (); } Catch(SQLException e) {e.printstacktrace (); }        }        if(Con! =NULL) {            Try{con.close (); } Catch(SQLException e) {e.printstacktrace (); }        }    }}

Dao

 PackageCom.swift.dao;Importjava.sql.Connection;Importjava.sql.SQLException;ImportOrg.apache.commons.dbutils.QueryRunner;ImportOrg.apache.commons.dbutils.handlers.BeanHandler;ImportOrg.apache.commons.dbutils.handlers.ScalarHandler;ImportCn.itcast.domain.Account;Importcn.itcast.tools.JDBCUtils; Public classDao {PrivateQueryrunner QR =NewQueryrunner (); PrivateConnection con=jdbcutils.getconnection ();  Public voidQuerysenderbalance (String cardid1,DoubleMoneythrowsSQLException {String SQL= "SELECT * from Account WHERE cardid=?;"; Beanhandler<Account> rsh =NewBeanhandler<account> (account.class); Account Bean=qr.query (con, SQL, rsh, CARDID1);        System.out.println (Bean); DoubleBalance =bean.getbalance ();        System.out.println (balance); if(Balance <Money ) {System.out.println ("Insufficient balance!" "); System.exit (0); } Else{System.out.println ("The balance is enough!" "); }    }         Public intZhuanchu (String Cardid,DoubleMoneythrowsSQLException {String Chaxun= "Select Moneyrate from account where cardid=?"; DoubleRate= (Double) Qr.query (Con,chaxun,NewScalarhandler (), cardid); Doublemoneyrate=money*rate/100;        System.out.println (moneyrate); String Shengyu= "UPDATE account SET balance =balance-?-? WHERE cardid=?; "; returnqr.update (Con, Shengyu, money,moneyrate,cardid); }     Public intZhuanru (String Cardid,DoubleMoneythrowsSQLException {String Zengjia= "UPDATE account SET balance =balance+?" WHERE cardid=?; "; returnqr.update (Con, Zengjia, money,cardid); }     Public intWriteinfo (String Cardid, String Tratype,DoubleMoney,string tradate)throwsSQLException {String info= "INSERT into transaction (cardid,tratype,tramoney,tradate) values (?,?,?,?);"; returnqr.update (Con, info, cardid,tratype,money,tradate); }                }

Service

 PackageCom.swift.service;Importjava.sql.Connection;Importjava.sql.SQLException;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportCom.swift.dao.Dao;Importcn.itcast.tools.JDBCUtils; Public classService {PrivateConnection con=jdbcutils.getconnection ();  Public voidTransfer (String cardid1, String Cardid2,DoubleMoney ) {        Try{con.setautocommit (false); DAO DAO=NewDao ();            Dao.querysenderbalance (CARDID1, money); intchu=Dao.zhuanchu (CARDID1, money); intru=Dao.zhuanru (Cardid2, money);            Con.commit (); if(chu>0&&ru>0) {System.out.println ("The transfer was successful."); } Date Date=NewDate (); SimpleDateFormat SDF=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String Tradate=Sdf.format (date); Dao.writeinfo (CARDID1,"Turn Out", Money, tradate); Dao.writeinfo (Cardid2,Into, Money, tradate);        Con.commit (); } Catch(Exception e) {System.out.println ("Exception ready to roll back.");            E.printstacktrace (); Try{con.rollback (); } Catch(SQLException E1) {e1.printstacktrace (); }        } finally {            if(Con! =NULL) {                Try{con.close (); } Catch(SQLException e) {e.printstacktrace (); }            }        }    }}

Client

 Package com.swift.client; Import Com.swift.service.Service;  Public class Client {    publicstaticvoid  main (string[] args) {        = " 6212999999999 ";         = "6212888888888";         Double money = +;                Service s=new  Service ();        S.transfer (CARDID1, Cardid2, Money);}            }

Java MySQL multiple transaction simulation based on exchange rate transfer, and storage transfer information layered complete DAO Layer Service Layer client layer connection pool use C3P0 write to library using dbutils

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.