当前位置:网站首页>JDBC call stored procedure, MySQL trigger
JDBC call stored procedure, MySQL trigger
2022-06-23 05:11:00 【clear0217】
JDBC Calling stored procedure
The load driver Class.forName
Create database connection conn= DriverManager.getConnection
Create processing block CallableStatement cs = conn.prepareCall
Put in the parameters prepareCall.setString
Execute stored procedures prepareCall.execute()
Close the connection
Parameterless stored procedures
create procedure p1() begin
select * from t_users;
end;
-- Command line call call p1();
JDBC Code call
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:///test?serverTimezone=UTC", "root", "123456");
CallableStatement cs = conn.prepareCall("{call p1()}");
cs.execute();
ResultSet rs = cs.getResultSet();
while(rs.next()){
System.out.println(rs.getLong("id")+"\t"+rs.getString(2) +"\t"+rs.getDate("birth"));
}
rs.close();
cs.close();
conn.close();
Stored procedure definition with parameters
CREATE PROCEDURE add_pro(a INT,b INT,OUT ret INT)
BEGINSET
ret=a+b;
END
-- Calling method
call add_pro(1,2,@cc);
select @cc;
Calling stored procedure
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:///test? serverTimezone=UTC", "root", "123456");
CallableStatement cs = conn.prepareCall("{call add_pro(?,?,?)}");
cs.setInt(1, 123);
cs.setInt(2, 300);
cs.registerOutParameter(3, Types.INTEGER);
// Process the return value in the parameter Register the return value type
cs.execute();
int res=cs.getInt(3);
// Get the return value of the output parameter
System.out.println(res);
cs.close();
conn.close();
Special stored procedure parameters inout
CREATE PROCEDURE mul_pro(inout ret INT)
BEGINSET
ret=ret*11;
END
-- How to call the command line
set @cc=5;
call mul_pro(@cc);
select @cc;
JDBC call
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:///test? serverTimezone=UTC", "root", "123456");
CallableStatement cs = conn.prepareCall("{call mul_pro(?)}");
cs.setInt(1, 9);
cs.registerOutParameter(1, Types.INTEGER);
// Process the return value in the parameter Register the return value type
cs.execute();
int res=cs.getInt(1);
System.out.println(res);
cs.close();
conn.close();
A stored procedure contains multiple query result sets
create procedure show1 (aid bigint)
begin
select * from t_users where id=aid;
select * from t_roles where id=aid;
end;
-- Command line call
call show1(2);
JDBC call
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql:///test? serverTimezone=UTC", "root", "123456");
CallableStatement cs = conn.prepareCall("{call show1(?)}");
cs.setLong(1, 2L);
cs.execute();
ResultSet rs = cs.getResultSet();
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("====================");
while (rs.next()) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.print(rs.getObject(i) + "\t");
}
}
System.out.println(); // You need to customize the method to get data , Otherwise, the code to get the data part appears many times
while (cs.getMoreResults()) {
rs = cs.getResultSet();
rsmd = rs.getMetaData();
System.out.println("====================");
while (rs.next()) {
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.print(rs.getObject(i) + "\t");
}
}
System.out.println();
}
rs.close();
cs.close();
conn.close();
MySQL trigger
A trigger is a database object , Is to insert in the data table 、 Delete 、 Operations such as update , And then it automatically triggers the pre
Some articles made up first SQL Execution of statements
characteristic
The operation that triggers the event and the... In the trigger SQL Statement is a transaction operation , It's atomic , Or all , Either not . such as : bank transfer .
advantage
- SQL Triggers provide an alternative way to check data integrity
Checking constraints
create table t1(id int,name varchar(32),age int check(age between 18 and 65));The database engine needs to use innodb,innodb Storage engine support transactions 、 Foreign keys and checking constraints . Check type constraint settings
In the table , No syntax errors , however DBMS It's not going to be checked
SQL Triggers can catch errors in the business logic in the database layer .
SQL Triggers provide another way to run scheduled tasks . By using SQL trigger , You don't have to wait to run a scheduled task , Because triggers are automatically called before or after changes are made to the data in the table
MySQL For disaster tolerance , Generally, the database needs to be backed up . The general schedule for backups is weekly 1 Full volume backup , Other time incremental backups . The backup time is generally selected to be performed at the time end with the least access , for example 0 Point to 1 Between points , You can schedule tasks or use triggers to automate backups
- SQL Triggers are very useful for auditing changes to data in a table .
shortcoming
SQL Triggers can only provide extended validation , And cannot replace all validations . Some simple validation has to be done at the application layer . For example, you can use JavaScript Or the server-side uses the server-side scripting language to verify the user input of the client
Calling and executing from a client application SQL Trigger not visible , So it's hard to figure out what's going on in the database layer .
SQL Triggers can increase the overhead of the database server .
Basic grammar
CREATE TRIGGER trigger_name Trigger Name trigger_time Triggering event trigger_event Triggering event
ON table_name The name of the table FOR EACH ROW [trigger_order]
trigger_body
Trigger_time: Trigger execution time : AFTER | BEFORE
Trigger_event: Events triggered by triggers : INSERT | UPDATE | DELETE
MySQL The triggers in can be divided into 3 Categories:
- FOR EACH ROW: Indicates that the trigger event will be triggered if the operation on any record satisfies the trigger event
Triggers can be divided into row level trigger and statement level trigger
Table_name: Indicates the name of the trigger event operation table
Trigger_body: To create a trigger SQL sentence
Typical applications
- BEFORE INSERT : Before inserting data , Check whether the inserted data conforms to the business logic , If not, an error message will be returned
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-C0IMpQt0-1655543092453)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220618165527770.png)]
- AFTER INSERT : In the table A After creating a new account , Automatically write the creation success information to the table B in . Typical reconciliation processing
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-JSb74LQV-1655543092455)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20220618165609680.png)]
auto_increment problem :
insert Operation is only new surface , No, old surface . If the column auto_increment, be before when new.id The value is 0,after when new.id It is newly generated id value
- BEFORE UPDATE : Before updating the data , Check whether the updated data conforms to the business logic , If not, an error message will be returned
CREATE TRIGGER validate_customer_level
BEFORE UPDATE
ON customers
FOR EACH ROW
IF OLD.level='VIP' THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'VIP Level customers cannot be downgraded to normal level customers ';
END IF
update Table existing old It stores the data that needs to be replaced , And then there is new It is the data that needs to be newly added .old yes update Previous data ,new yes update Later data
- AFTER UPDATE : After updating the data , Record the operation behavior in log in
CREATE TRIGGER log_sales_updates
AFTER UPDATE
ON sales
FOR EACH ROW
Insert into audit_log(sales_id, previous_amount, new_amount, updated_by, updated_on) VALUES (NEW.sales_id The new data ,OLD.sales_amount Old data ,
NEW.sales_amount,(SELECT USER()), NOW())
BEFORE DELETE : Before deleting data , Check whether there is associated data , if there be , Stop deletion
CREATE TRIGGER validate_related_records BEFORE DELETE ON customers FOR EACH ROW IF OLD.customer_id in (select customer_id from sales) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = ' This customer has an associated sales record , Can't delete .'; END IF;The deletion operation can be divided into logical deletion and physical deletion , Basically, they are all logical deletion , The so-called logical deletion refers to adding a column in the table to identify whether the row data has been deleted ,deleted boolean default 0.delete Operation is only old surface , Where the data to be deleted is stored , No, new surface
AFTER DELETE : Delete table A After the message , Automatically delete table B Middle and table A Associated information .
CREATE TRIGGER delete_related_info AFTER DELETE ON sales FOR EACH ROW Delete from customers where customer_id=OLD.customer_id;
View memory
SHOW TRIGGERS; See which triggers are in the database
SHOW CREATE TRIGGER trigger_name;
NEW and OLD Application
MySQL It defines NEW and OLD Two temporary tables , Used to represent the table where the trigger is located , Which line of data triggers the trigger , To refer to the changed record content in the trigger , Whether the specific modification can take effect depends on whether the transaction is committed or rolled back
stay INSERT Type trigger ,NEW It is used to intercept and save the information about (BEFORE) Or already (AFTER) New data inserted ;
stay UPDATE Type trigger ,OLD Used to intercept and save the original data that will be or has been modified ,NEW Used to intercept and save new data that will or has been modified to .
stay DELETE Type trigger ,OLD Used to intercept and save the original data that will be or has been deleted
Delete trigger
DELETE TRIGGER trigger_name;
Application restrictions
Triggers can take advantage in limited situations , Like statistics 、 Data table change log, etc . But there are also some flaws , For example, big data updates are triggered line by line , It reduces efficiency . And that is ,MyISAM The engine cannot guarantee atomicity . therefore , It depends on whether there are triggers in the application scenario .
The cursor
Cursors provide a flexible way to operate , Be able to locate each record in the result set , A data structure that operates on the data in the pointed record . Cursor let SQL This set oriented language has the ability of process oriented development in SQL in , A cursor is a temporary database object , Can point to the data row pointer stored in the database table . Here the cursor acts as a pointer , You can manipulate data rows by manipulating cursors .
advantage
Allows the program to query statements select Each row in the returned row set performs the same or different operation , Instead of performing the same operation on the entire row set
Provides the ability to delete and update rows in a table based on cursor position
Cursors are actually a collection oriented database management system RDBMS And line oriented programming , Make these two processing methods communicate through cursors .
shortcoming
Cursors cause some performance problems , For example, in the process of using cursors , Data rows will be locked , In this way, when there is a large amount of business concurrency , It will not only affect the efficiency between businesses , It also consumes system resources , Cause insufficient memory , This is because cursors are processed in memory .
principle
Cursor is to extract the corresponding data set according to the specified requirements , Then the data is processed one by one . The order of using cursors : Reputation cursor 、 Open cursor 、 Reading data 、 Close cursor 、 Delete cursor .
Trigger limit
mysql Trigger coverage criteria SQL All functions defined in , however , There are also some limitations to using them in applications :
Use in SHOW,LOAD DATA,LOAD TABLE,BACKUP DATABASE,RESTORE,FLUSH and RETURN Above statement
Use implicit or explicit commit or rollback statements , Such as COMMIT,ROLLBACK,START TRANSACTION,LOCK/UNLOCK TABLES,ALTER,CREATE,DROP,RENAME etc.
Use the prepare statement , Such as PREPARE,EXECUTE etc.
Usage dynamics SQL sentence
Attention problem
from MySQL 5.7.2+ Version start , Multiple triggers can be defined for the same trigger event and action time . When used or not used INSERT,DELETE or UPDATE Statement changes the statement of data in the table , Triggers associated with tables are not called . for example ,truncate Statement to delete all data from a table , But do not call the trigger associated with the table . however , Some statements use the background INSERT sentence , Such as REPLACE Sentence or LOAD DATA sentence . If you use these statements , The corresponding trigger associated with the table is called . So you must use a unique name for each trigger associated with the table . You can define the same trigger name for different tables , This is a good way .
边栏推荐
- 单行或多行文本溢出,省略号代替
- 395. redundant path
- apache atlas 快速入门
- 笔者认为所谓的产业互联网,就是一个产业与互联网深度融合的过程
- UI automation positioning edge -xpath actual combat
- mongodb分片原理
- centos7安装postgresql8.2.15及存储过程创建
- Icer Skill 02makefile script Running VCS Simulation
- Parameter passing of 18 generator function
- 微信小程序:微信也可以发闪照了闪照制作生成微信小程序源码下载,自定义闪照时间
猜你喜欢

GNSS速度解算的三种方法

Shadertoy基础教学01、画圆(smoothstep()函数讲解)

三层架构实验

618如何冲出重围?海尔智家:做好用户的数字化

Object structure diagram, which can quickly illustrate the internal structure of an object

How to use data to tell a wonderful story?

How can mushrooms survive a five-year loss of 4.2 billion yuan?
![[OFDM communication] simulation of OFDM multi-user resource allocation based on MATLAB [including Matlab source code 1902]](/img/ad/91a81c7f413484a86adcff8fc84e3b.jpg)
[OFDM communication] simulation of OFDM multi-user resource allocation based on MATLAB [including Matlab source code 1902]

【Mac】安全性与隐私中没有任何来源选项

rtklib2.4.3 b34 单点定位的一个bug
随机推荐
【Laravel系列7.8】广播系统
[graph theory] - bipartite graph
新晋职场人的 技术进击?之旅
Learn to draw Er graph in an article
Brief ideas and simple cases of JVM tuning - why do you need JVM tuning?
直接插入排序——【常见排序法(1/8)】
② Cocoapods principle and podspec file uploading operation
Seven year manong Road
Shadertoy basic teaching 02. Drawing smiling faces
8年经验之谈:月薪3000到30000,测试工程师的变“行”记
Small problems in the spoole framework for TCP communication in PHP
dolphinscheduler 1.2.1 数据迁移到 dolphinscheduler 2.0.5方法及迁移后数据测试记录
How to use data to tell a wonderful story?
vmware网络连接出错Unit network.service not found
单行或多行文本溢出,省略号代替
Banner banner
dolphinscheduler海豚调度升级代码改造-UpgradeDolphinScheduler
What are the main aspects of visual improvement brought by introducing AI into ISP Technology
The solution to prompt "this dictionary creation could be rewritten as a dictionary literal" when updating the dictionary key value in pychart
UI自动化定位利器-xpath实战