当前位置:网站首页>Design and implementation of database for banking system

Design and implementation of database for banking system

2022-06-13 11:40:00 Good night to you

The design and implementation of the database of banking system

1. Create database banking system database ---bankDB

Drop database if EXISTS bankDB; # Delete bindDB database , There is no error even if there is no database 
CREATE database bankDB;# Create database 

2. Create customer table ---userInfo

Field name data type meaning explain
customerIDint Customer number Auto increment , from 1 Start , Primary key
customerNamevarchar Account name Required
PIDchar ID number Required , Can only be 18 position , Unique constraint
telephonevarchar contact number Required , The format is fixed telephone or mobile phone number
addressvarchar Residential address Optional input
use bankDB;# Using a database 
drop table  if exists userInfo;# Delete userInfo Data sheet , No error even if there is no data table 
create table userInfo  # establish userInfo Data sheet --- Customer list 
(  
customerID int auto_increment PRIMARY key,  # Customer number , Auto increment , from 1 Start , Primary key 
customerName varchar(20) not null, # Account name , Required but not blank 
PID CHAR(18) NOT NULL, # ID number , Required but not blank 
telephone varchar(15) not null, # Phone number , Required but not blank 
address varchar(50) # Address , Can be null 
);
alter table userInfo add CONSTRAINT UQ_PID UNIQUE(PID);  
# to userInfo Tabular PID Add a unique constraint 
desc userInfo; # View the table structure of the data table 

3. Create a bank card table ---cardInfo

Field name data type meaning explain
cardIDchar Card number Required , Primary key .
curIDvarchar Type of currency Foreign keys , Required , The default is RMB
savingIDtinyint Type of deposit Foreign keys , Required
openDatedatetime Account opening date Required , It defaults to the current system date and time
openMoneydouble Account balance Required
balancedouble balance Required
passwordchar password Required ,6 Digit number , When opening an account, it defaults to 6 individual 8
isReportLosschar Whether to report the loss Required , yes / no , The default value is no
customerIDint Customer number Foreign keys , Required
drop table  if exists cardInfo;# Delete cardInfo Data sheet , No error even if there is no data table 
create table cardInfo   # establish cardInfo Data sheet --- Bank card form 
( 
cardID char(19) not null, # Card number , Required but not blank 
curID varchar(10) not null,# Type of currency , Required but not blank 
savingID int not null, # Type of deposit , Required but not blank 
openDate Datetime not null,# Account opening date , Required but not blank 
openMoney DOUBLE not null,# The amount of the account , Required but not blank 
balance DOUBLE not null,# balance , Required but not blank 
password char(6) not null,# password ,6 Digit number , When opening an account, it defaults to 6 individual 8, Required but not blank 
isReportLoss char(1) not null,# Whether to report the loss , yes / no , The default value is no , Required but not blank 
customerID int not null# Customer number , Foreign keys .
);
desc cardInfo;

4. Create a transaction table

Field name data type meaning explain
tradeDatedatetime Transaction date Required , It defaults to the current system date and time
cardIDvarchar Card number Foreign keys , Required
tradeTypechar Type of transaction Required , Only deposit / draw
tradeMoneydouble Transaction amount Required , Greater than 0
machinechar Terminal number The machine number of the customer's business operation
drop table  if exists tradeInfo;# Delete tradeInfo Data sheet , No error even if there is no data table 
create table tradeInfo # establish tradeInfo Data sheet --- Deal sheet 
( 
tradeDate datetime not null,# Transaction date , Required , It defaults to the current system date and time 
tradeType enum(" Deposit in "," spending ") not null,# Type of transaction , Required but not blank , Only deposit / draw 
cardID char(19) not null, # Card number , Foreign keys , Required but not blank 
tradeMoney DOUBLE not null,# Transaction amount , Required but not blank , Default >0
machine char(8) not null# Terminal number , The default value is not empty 
);
desc tradeInfo;

5. Deposit type table structure

Field name data type meaning explain
savingIDtinyint Deposit type number Auto increment , from 1 Start , Primary key
savingNamevarchar Deposit type name Required
descriptvarchar describe Can be empty
drop table  if exists deposit;# Delete deposit Data sheet , No error even if there is no data table 
create table deposit   # establish deposit Data sheet ---> Deposit type table 
(  
savingID INT AUTO_INCREMENT PRIMARY KEY, # Deposit type number , Auto increment from 1 Start , Primary key 
savingName varchar(20) not null,# Deposit type name , Required but not blank 
descript varchar(50)# describe 
);
desc deposit;

6. to cardInfo Add constraints to the table

alter table cardInfo add CONSTRAINT PK_cardID PRIMARY key(cardID);
​
# to cardID Add a primary key constraint 
​
alter table cardInfo ALTER curID SET DEFAULT "RMB";
​
# to curID Set a default option to RMB
​
alter table cardInfo MODIFY COLUMN openDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;
​
# The account opening date is set to the current system time by default 
​
alter table cardInfo ALTER password SET DEFAULT "888888";
​
# to password Set a default option to 888888
​
alter table cardInfo alter isReportLoss SET DEFAULT 0;
​
# to isReportLoss Set the default option to 0.1 be for the purpose of ,0 Why not 
​
alter table cardInfo add CONSTRAINT FK_customerID FOREIGN key(customerID) REFERENCES userInfo(customerID);
​
# Set up foreign keys ,cardInfo by userInfo Subordinate table of ,customerID Reference is userInfo Customer number of the table 
​
alter table cardInfo add CONSTRAINT FK_savingID FOREIGN key(savingID) REFERENCES deposit(savingID); 
​
# Set up foreign keys ,cardInfo by userInfo Subordinate table of ,savingID Reference is userInfo Deposit type no. of the table 
​
desc cardInfo;

7. to tradeInfo Add constraints to the table

alter table tradeInfo add CONSTRAINT PK_cardID_tradeInfo PRIMARY key(cardID,tradeDate);
​
# stay tardeInfo Set... In the table cardID,tradeDate For union primary key 
​
alter table tradeInfo add CONSTRAINT FK_cardID FOREIGN key(cardID) REFERENCES cardInfo(cardID);
​
# Set up foreign keys ,tradeInfo by cardInfo Subordinate table of ,cardID Reference resources cardInfo Your card number 
​
alter table tradeInfo MODIFY COLUMN tradeDate datetime not null DEFAULT CURRENT_TIMESTAMP;
​
# Set up tradeInfo The transaction date of the table is a non empty constraint , The default is the current system date 
​
alter table tradeInfo modify machine char(8) DEFAULT 1;
​
# Set the terminal number to... By default 1
​
create index IX_cardID on tradeInfo(cardID);
​
# stay tradeInfo Use on the table create index  Statement to create an index named IX_card
# Grammatical structure :create [unique( unique index )] [fulltext( Full-text index )] [spatial( Spatial index )] index  Index name  on  Table name ( Field name [( length )][asc|desc][,....]);

8. Insert data into the deposit type table

insert into deposit(savingName,descript) VALUES (' current ',' Interest shall be settled on the deposit date ');
insert into deposit(savingName,descript) VALUES (' Regular for one year ',' The deposit period is one year ');
insert into deposit(savingName,descript) VALUES (' Regular for two years ',' The deposit period is two years ');
insert into deposit(savingName,descript) VALUES (' Regular for three years ',' The deposit period is three years ');
insert into deposit(savingName) VALUES (' According to the rules ');
insert into deposit(savingName,descript) VALUES (' One year for petty cash deposit and lump sum withdrawal ',' The deposit period is one year ');
insert into deposit(savingName,descript) VALUES (' Two years of petty cash deposit and withdrawal ',' The deposit period is two years ');
insert into deposit(savingName,descript) VALUES (' Zero deposit and lump sum withdrawal for three years ',' The deposit period is three years ');
select * from deposit; # see deposit Table data 
​
# Insert full record :insert into  Table name ( Field 1, Field 2,....) values (' Field 1 Corresponding data 1',' Field 2 Corresponding data 2');
# View the data :select  Field name  form  Table name ;

9. Insert data into the customer information table

INSERT into userInfo(customerName,PID,telephone,address) VALUES 
(' Zhou also ','431281200108193619','0719-26224941',' Wuchang District, Wuhan City, Hubei Province '),
(' Wang Ke ','441391200201294618','0729-44624944',' Hongshan District, Wuhan City, Hubei Province '),
(' Ho ho ','42128120020413463X','0749-21227409',' Qingshan District, Wuhan City, Hubei Province '),
(' Wang Hanyu ','761212200308191682','0927-22492341',' Huarong District, Ezhou City, Hubei Province '),
(' ruban ','663221200308211352','1127-52592652',' Huarong District, Ezhou City, Hubei Province ');
select * from userInfo;
​
# Insert part of the data record 
insert into  Table name ( Field 1, Field 2,......) values 
(' Field 1 Corresponding data 1',' Field 2 Corresponding data 2',.....),
(' Field 1 Corresponding data 1',' Field 2 Corresponding data 2',.....),
(' Field 1 Corresponding data 1',' Field 2 Corresponding data 2',.....);

10. Insert data into the bank card table

INSERT into cardInfo(cardID,savingID,openMoney,balance,customerID) VALUES 
('6227 2666 1234 5678',1,1000,1000,1),
('6227 2666 5678 1234',2,6000,6000,2),
('6227 2666 1432 5876',3,9000,9000,3),
('6227 2666 1234 5666',4,2500,2500,4),
('6227 2666 1234 5888',5,3600,3600,5); 
select * from cardInfo;

11. Insert data into the transaction table

INSERT into tradeinfo(tradeType,cardID,tradeMoney) VALUES (' spending ','6227 2666 1234 5678',900);
​
# Insert transactions in the transaction table 
​
UPDATE cardInfo SET balance = balance-900 where cardID = '6227 2666 1234 5678';
​
# Update the existing balance in the bank card table .
​
INSERT into tradeinfo(tradeType,cardID,tradeMoney) VALUES (' Deposit in ','6227 2666 5678 1234',5000);
​
# Insert transactions in the transaction table 
​
UPDATE cardInfo set balance = balance+5000 where cardID = '6227 2666 5678 1234';
​
# Update the existing balance in the bank card table .
​
INSERT into tradeinfo(tradeType,cardID,tradeMoney) VALUES (' spending ','6227 2666 1432 5876',1000);
​
# Insert transactions in the transaction table 
​
UPDATE cardInfo set balance = balance-1000 where cardID = '6227 2666 1432 5876';
​
# Update the existing balance in the bank card table .
​
INSERT into tradeinfo(tradeType,cardID,tradeMoney) VALUES (' Deposit in ','6227 2666 1234 5666',3000);
​
# Insert transactions in the transaction table 
​
UPDATE cardInfo set balance = balance+3000 where cardID = '6227 2666 1234 5666';
​
# Update the existing balance in the bank card table .
​
INSERT into tradeinfo(tradeType,cardID,tradeMoney) VALUES (' Deposit in ','6227 2666 1234 5888',1000);
​
# Insert transactions in the transaction table 
​
UPDATE cardInfo set balance = balance+1000 where cardID = '6227 2666 1234 5888';
​
# Update the existing balance in the bank card table .
​
select * from cardInfo; # View the bank card information table data  ---> result 1
select * from tradeInfo; # View transaction table data ---> result 2

12. To write SQL Statements for

1. Change customer password

# modify customerID=1, Zhou Ye's bank card password 
​
UPDATE cardInfo set password = '123456' where cardID = '6227 2666 1234 5678';
​
# modify customerID=3, Ho Ho's bank card password 
​
UPDATE cardInfo set password = '654321' where cardID = '6227 2666 1432 5876';
​
select * from cardInfo;# View the bank card information table 
​
​
# Modification of table records :UPDATE sentence 
# Grammar format :update [ Optional parameters ]  Data table name  set  Field 1= value 1[, Field 2= value 2....] [where  Conditional expression ] [orderby] [limit]
# Optional parameters :low_priority, Indicates the available latency when multiple users access the database UPDATE operation , Until no other user reads the data , This procedure is only applicable to the storage engine of table level lock .                      ignore: stay mysql in , If an error occurs in the update statement , Whole update Statement operations are canceled , All rows updated by the error are restored to their original values . therefore , In order to continue when errors occur            to update , have access to ignore Parameters 
#set: Specify the field name and its value to be modified in the data table . The value can be an expression , It can also be the default value corresponding to this field . If you want to set default values , You need to use the keyword default.
#where: Used to limit the rows in the table to be modified , If the clause is not specified , that update Statement will update all rows in the table .
#orderby: Used to limit the order in which rows in the table are modified 
#limit: Used to limit the number of lines modified 

2. Report the loss of bank card

# Zhou also accidentally lost his bank card , Apply for loss reporting service 
​
update cardInfo set isReportLoss = 1 where cardID = '6227 2666 1234 5678';
select * from cardInfo;
​
​
# View the password modification and loss report results 
​
select cardID,curID,savingName,openDate,openMoney,balance,password,
case isReportLoss
    when  1 then ' Report the loss of '
    when  0 then ' The loss has not been reported '
end,customerName 
from cardInfo INNER JOIN deposit on cardInfo.savingID = deposit.savingID
INNER JOIN userInfo on cardInfo.customerID = userInfo.customerID;
​
​
#case Statement is a conditional judgment statement , It is used to judge the large program structure by multiple branches 
case  expression 
when when_value then statement_list;
[when when_value then statement_list;].....
else select 'good';
end case;
 If when_value The value of the expression matches the value of , execute then After keyword statement_list sentence .
 If when_value The values of the expressions do not match , execute else The statement after the keyword .
# Multi-table query :
# Rule of grammar :
select [ Table name .]  Target field name  [AS  Alias ]
from  Left table name [AS  Alias ]  Connection type   Right table name [AS  Alias ]
on  Connection condition 
[where  Conditional expression ];
# Connection types and operators :
1.cross join: Cross connect 
2.inner join or join: Internal connection 
3.left join or left outer join: The left outer join 
4.right join or right outer join: Right connection 
5.full join or full outer join: Complete connection 

3. Check the account opening information of this week

#date_sub() Function to subtract a specified time interval from a date . Grammar format :
​
#data_sub(date,INTERVAL expr type)
​
# Parameter description :date: Legal date expression ,expr: Specified time interval .
​
#type: Interval type , Yes miscrosecond,seconde,minute,hour,day,week,mounth,year etc. 
​
select cardInfo.cardID,userInfo.customerName,cardInfo.curID,deposit.savingName,cardInfo.openDate,cardInfo.openMoney,cardInfo.balance,
case cardInfo.isReportLoss
when 1 then ' Loss reporting account '
when 2 then ' Normal account '
end
from cardInfo cardInfo INNER join userInfo on cardInfo.customerID = userInfo.customerID
INNER join deposit  on cardInfo.savingID=deposit.savingID  
where openDate > DATE_SUB(CURDATE(),INTERVAL 1 week); # Non equivalent connection 
​
# Internal connection :select  List of field names  from  Table name 1 inner join  Table name 2 on  Table name 1  Field name   Comparison operator   Table name 2  Field name ;

4. Query the card number with the highest transaction amount in this month

select DISTINCT cardID from tradeInfo  #Distinct: Remove duplicate card numbers 
where tradeMoney = (SELECT MAX(tradeMoney) from tradeInfo # Using subqueries 
WHERE tradeDate > DATE_SUB(CURDATE(),INTERVAL 1 MONTH)); # The time is this month 
​
​
#DATE_SUB() function ----> Subtract the specified time interval from the date .
 Rule of grammar :DATE_SUB(date,INTERVAL expr type)
type  The parameters can be the following values :
MICROSECOND # microsecond 
SECOND # Number of seconds 
MINUTE # Minutes 
HOUR   # Hours 
DAY    # Days 
WEEK   # Weeks 
MONTH  # Monthly number 
QUARTER # quarter 
YEAR   # number of years 
.......
​
​
#CURDATE----> Get the current date of the system 

5. Inquire about the customer who reported the loss

select customerName,telephone from userInfo 
where customerID in(SELECT customerID from cardInfo where isReportLoss =1);
​
# Inquire about the customer who reported the loss , Display the name and telephone number of the customer who reported the loss 
#SELECT customerID from cardInfo where isReportLoss =1  Query the bank card information table isReportLoss =1 Of users ID

6. Dunning prompt business

# According to some kind of business ( Such as paying telephone charges , Pay mobile phone fee on behalf of others ) The need for , At the end of each month , If the balance on the customer's account is found to be less than 1100 element , The bank will uniformly call for payment .
# Using link queries or subqueries 
select customerName,telephone,balance 
from userInfo INNER JOIN cardInfo 
on cardInfo.customerID = userInfo.customerID
where balance<1100;

13. establish , Use view

1. establish view_user Try :

### In order to display information to customers, friendly , All fields required to query each table are Chinese field names .
# Output bank customer records 

drop view if EXISTS view_user; # Delete view_user Try , Avoid that there are already in the database view_user View 
create view view_user
AS
select customerID as  Customer number ,customerName as  Account name ,PID AS  ID number ,telephone as  Phone number ,address as  Residential address  from userInfo;

select * from view_user;# View view details 


# View creation 
create [or replace] [algoritm]={undefined|merge|temptable} 
view view_name [( List of field names )]
as select sentence   [with[cascaded|local] check option]

2. establish view_card Try :

# Output bank card records 
drop view if exists view_card; 
create view view_card 
AS
SELECT cardinfo.cardID  Card number ,userinfo.customerName  Name of customer ,cardinfo.curID  Type of currency ,deposit.savingName  Type of deposit ,cardinfo.openDate  Account opening date ,cardinfo.balance  balance ,cardinfo.password  password ,
case cardinfo.isReportLoss
when 1 then ' Report the loss of '
when 0 then ' normal '
end  Account status 
from cardinfo INNER JOIN userInfo  on cardinfo.customerID=userinfo.customerID INNER JOIN deposit on cardinfo.savingID = deposit.savingID;
SELECT * from view_card; 

3. establish view_trade Try :

# Transaction information view 

drop view if EXISTS view_trade;
CREATE view view_trade 
AS
SELECT tradeDate as  Transaction date ,tradeType as  Type of transaction ,cardId as  Card number ,tradeMoney as  Trading money ,machine as  Terminal number  from tradeInfo;
select * from view_trade;

14. Use transactions and stored procedures to implement business processing

1. Complete deposit or withdrawal business

Drop PROCEDURE if EXISTS trade_proc;
CREATE PROCEDURE trade_proc(IN t_type char(2),In t_money DOUBLE,in card_id char(19),in m_id char(8))
MODIFIES sql DATA  # Indicates that the subroutine contains data to be written SQL sentence .
BEGIN
 DECLARE ye DOUBLE; # Declare variables ye by double type 
 start TRANSACTION; # Start transaction 
 if(t_type=" draw ")then
  INSERT into tradeinfo(tradeType,cardID,tradeMoney,machine)  VALUES (t_type,card_id,t_money,m_id); 
	UPDATE cardinfo set balance = balance - t_money where cardID = card_id;
    if(ye <0) then 
	SELECT " Lack of balance ";
	ROLLBACK;# Roll back the transaction 
	else
	COMMIT;# Save in database 
	end if;
end if;
if(t_type=" Deposit in ")then
 INSERT into tradeinfo(tradeType,cardID,tradeMoney,machine)  VALUES (t_type,card_id,t_money,m_id);
	UPDATE cardinfo set balance = balance + t_money where cardID = card_id;
	COMMIT;
    end if;
end;
	
# Create and call stored procedures without input parameters 
create procedure   The process of ()
begin
mysql sentence 
end;

#if The sentence judges the condition according to the logical relationship ture still false, Go to execute the statement in the corresponding branch 
# Grammatical structure :
if expr_condition then 
   statement_list
elseif expr_condition then 
   statement_list
else statement_list
end if;

2. Generate random card number

# Of random functions rand Use 
#rand( Random seeds )
# Will produce 0~1 The random number , The random seeds are required to be different each time . To ensure that random seeds are different every time , The commonly used algorithm is :
# Random seeds = The current month *10000+ Current minutes *1000+ Current seconds *100
# produce 0~1 After the random number of , Take the decimal point 8 by , namely 0.xxxxxxxx

DROP PROCEDURE IF EXISTS use_randCardID;
CREATE PROCEDURE use_randCardID(OUT randCardID char(19))
BEGIN
    DECLARE r DECIMAL(15,8); #declare Declare variables 
    DECLARE tempStr CHAR(10); 
    SELECT RAND((MONTH(NOW())*10000)+(MINUTE(NOW())*1000)+(SECOND(NOW())*100)) INTO r;
    SET tempStr=CONVERT(r, CHAR(10));#CONVERT()  Function is a general function that converts dates to new data types .
    SET randCardID=CONCAT('6227 2666 ', SUBSTRING(tempStr, 3, 4), ' ', SUBSTRING(tempStr, 7, 4));
END;

# Random card number generated by the test 

set @kh=" ";
call use_randCardID(@kh);
SELECT @kh;

3. Statistics of bank capital circulation amount and profit settlement

# Amount of funds in circulation = The total amount deposited - Total expenditure amount 

# Profit settlement = Total withdrawal amount x0.008- Total deposit amount x0.003

# Tips : Define two variables to store the total deposit amount and the total withdrawal amount . Use sum() Function to summarize , Use the conversion function convert()

# Calculate the amount of bank funds in circulation 
drop procedure if EXISTS profit_proc1;
create PROCEDURE profit_proc1(out y1 DOUBLE)
reads sql data
BEGIN
DECLARE l_in DOUBLE;
declare l_out DOUBLE;
SELECT sum(tradeMoney) into l_in from tradeinfo where tradeType = " Deposit in ";
SELECT sum(tradeMoney) into l_out from traneinfo where tradeType = " spending ";
set y1=l_out-l_in;
end;
# Calculate profit settlement 
drop PROCEDURE if EXISTS profit_proc2;
CREATE PROCEDURE profit_proc(out y2 DOUBLE)
reads sql data
BEGIN 
DECLARE l_in DOUBLE;
declare l_out DOUBLE;
SELECT sum(tradeMoney) into l_in from tradeinfo where tradeType = " Deposit in ";
SELECT sum(tradeMoney) into l_out from traneinfo where tradeType = " spending ";
set y2=l_out*0.008 - l_in*0.003;
end;

4. Transfer is realized by transaction

DROP PROCEDURE IF EXISTS useTradefer_proc;
CREATE PROCEDURE useTradefer_proc(
    IN outCard_id CHAR(19),
    IN inCard_id CHAR(19),
    IN z_je DOUBLE,
    IN m_id CHAR(4))
MODIFIES SQL DATA
BEGIN
    DECLARE ye DOUBLE;
    DECLARE err INT DEFAULT 0; #  Cumulative number of error messages 
    DECLARE errl INT DEFAULT 0;
--     DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET errl=1;
    #  Transfer in account does not exist 
		DECLARE bankCount INT DEFAULT 0;
		SELECT count(*) into bankCount FROM cardinfo WHERE cardID=inCard_id;
    IF !bankCount THEN
        SELECT " Transfer in account does not exist ";
        SET err=err+1;
				set errl = 1;
    END IF;
    #  The balance of the transfer out account is insufficient ( Less than the transfer amount )
    SELECT balance INTO ye FROM cardinfo WHERE cardID=outCard_id;
    IF(ye<z_je) THEN
        SELECT " Insufficient account balance ";
        SET err=err+1;
				set errl = 1;
    END IF;
    #  Transfer and record transaction information normally without error information 
    IF(err=0) THEN
        START TRANSACTION;      
        UPDATE cardinfo SET balance=balance-z_je WHERE cardID=outCard_id;       
        UPDATE cardinfo SET balance=balance+z_je WHERE cardID=inCard_id;        
        INSERT INTO tradeinfo(tradeType, cardID, tradeMoney, machine)
        VALUES(' spending ', outCard_id, z_je, m_id);       
        INSERT INTO tradeinfo(tradeType, cardID, tradeMoney, machine)
        VALUES(' Deposit in ', inCard_id, z_je, m_id);        
        #  If no error is reported, submit , If you report an error, roll back 
        IF(errl=1) THEN
            SELECT errl;
            ROLLBACK;
        ELSE
            COMMIT;
        END IF;
    END IF;
END;

call useTradefer_proc('6227 2666 1234 5666', '6227 2666 1234 5678',1,1);
SELECT * from tradeinfo;  ---> result 1
select * from cardinfo;   ---> result 2

原网站

版权声明
本文为[Good night to you]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206131120214182.html