简体   繁体   English

如何使用Java运行mysql存储过程

[英]how to run mysql stored procedure using java

I have a mysql stored procedure. 我有一个mysql存储过程。

DELIMITER //  
CREATE PROCEDURE GetRecordsByAge(IN Age INT)  
BEGIN 
  SELECT * FROM test1 WHERE age = Age;  
END //  
DELIMITER ;

When I run this stored procedure through java then it is giving all records of the table. 当我通过Java运行此存储过程时,它将给出表的所有记录。

But if I have a condition in select statement. 但是,如果我在select语句中有条件。 Why this is happening? 为什么会这样呢?

here is set of lines of my code:- 这是我的代码集:

CallableStatement cStmt = null;
cStmt = con.prepareCall("{ CALL GetSpecificRecord(?) }");
cStmt.setInt(1, 25);
cStmt.execute();
ResultSet rs1 = cStmt.getResultSet();

When I print this result set this will give all records of the table. 当我打印此结果集时,它将给出表格的所有记录。

Where is the problem? 问题出在哪儿?

Thanks 谢谢

The reason why you are getting all records is because of column name collision causing the WHERE clause to be always true. 获取所有记录的原因是由于列名冲突导致WHERE子句始终为true。 Change the name of the parameter that is not the same with the name of the column you are comparing with, 更改与要比较的列名称不同的参数名称,

DELIMITER //  
CREATE PROCEDURE GetRecordsByAge(IN _Age INT)  
BEGIN 
  SELECT * FROM test1 WHERE age = _Age;  
END //  
DELIMITER ;

The second is, you are calling different stored procedure. 第二个是,您正在调用不同的存储过程。 instead of GetRecordsByAge , you are calling GetSpecificRecord . 您正在调用GetSpecificRecord而不是GetRecordsByAge

Because the condition WHERE age = Age is always ture. 因为条件WHERE age = Age总是正确的。

Change the parameter name Age to something else: 将参数名称Age更改为其他名称:

DELIMITER //  
CREATE PROCEDURE GetRecordsByAge(IN AgeParam INT)  
BEGIN 
  SELECT * FROM test1 WHERE age = AgeParam;  
END //  
DELIMITER ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM