java 调用mysql存储过程

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
import java.sql.CallableStatement; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.Types; 



/* 
 * 对应的存储过程 
 DROP PROCEDURE IF EXISTS `pro_num_user`; 
delimiter ;; 
CREATE PROCEDURE `pro_num_user`(IN user_name varchar(10) ,OUT count_num INT) 
    READS SQL DATA 
BEGIN 
    SELECT COUNT(*) INTO count_num FROM tab_user WHERE 'name'=user_name; 
END 
 ;; 
delimiter ; 
 */ 
public class Test { 

    public static final String DRIVER_CLASS = "com.mysql.jdbc.Driver"; 
    public static final String URL = "jdbc:mysql://127.0.0.1:3306/test"; 
    public static final String USERNAME = "root"; 
    public static final String PASSWORD = "acbee"; 
    public static void main(String[] args) throws Exception { 
        test1(); 
        test2(); 
    } 
     
    public static void test1() throws Exception 
    { 
        Class.forName(DRIVER_CLASS); 
        Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); 
        String sql = "{CALL pro_num_user(?,?)}"; //调用存储过程 
        CallableStatement cstm = connection.prepareCall(sql); //实例化对象cstm 
        cstm.setString(1, "myd"); //存储过程输入参数 
        //cstm.setInt(2, 2); // 存储过程输入参数 
        cstm.registerOutParameter(2, Types.INTEGER); // 设置返回值类型 即返回值 
        cstm.execute(); // 执行存储过程 
        System.out.println(cstm.getInt(2)); 
        cstm.close(); 
        connection.close(); 
    } 
     
    public static void test2() throws Exception 
    { 
        Class.forName(DRIVER_CLASS); 
        Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); 
        String sql = "{CALL pro_number(?,?,?)}"; //调用存储过程 
        CallableStatement cstm = connection.prepareCall(sql); //实例化对象cstm 
        cstm.setInt(1, 2); // 存储过程输入参数 
        cstm.setInt(2, 2); // 存储过程输入参数 
        cstm.registerOutParameter(3, Types.INTEGER); // 设置返回值类型 即返回值 
        cstm.execute(); // 执行存储过程 
        System.out.println(cstm.getInt(3)); 
        cstm.close(); 
        connection.close(); 
         
    } 
} 


标签: Mysql

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:Java获取请求ip地址

下一篇:使用SpringMVC上传文件