Java 感知Mysql存储过程变量数量

系统 1279 0

 在项目中,可能会遇到sybase 移植到 mysql的情况,因为sybase 支持存储过程的可变参数,而mysql不能支持,所以,在调用mysql的时候,需要感知存储过程到底有几个参数,来合理的配置参数数量:

如下是代码

      package com.xxx.util;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

import java.util.Hashtable;

import java.util.Map;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class ProcedureHelper {

	

	/*是否是开发模式*/

	static boolean DEV = false;

	static Map<String,Integer> CACHE = new Hashtable<String,Integer>(100);  

	static Pattern PATTERN_ARGS = Pattern.compile("`\\s*\\((.*)\\)\\s*begin",Pattern.DOTALL|Pattern.CASE_INSENSITIVE);

	static Pattern PATTERN_ARG = Pattern.compile("(in|out|inout)[^-,]*(,|$)",Pattern.DOTALL|Pattern.CASE_INSENSITIVE);

	private static int doWork(Connection con,String proc) throws Exception {

		Statement stmt = null;

		stmt = con.createStatement(); //3、Statement 接口需要通过Connection 接口进行实例化操作

		ResultSet rs = stmt.executeQuery("show create procedure "+proc);

		

		if(rs.next()){

			//第三列为 存储过程的代码

			String code = rs.getString(3);

			Matcher m = PATTERN_ARGS.matcher(code);

			if(m.find()){

				String args = m.group(1);

				if(args.matches("\\s*"))

					return 0;

				else{

					Matcher m2 = PATTERN_ARG.matcher(args);

					int num = 0;

					while(m2.find()){

						//System.out.println(m2.group());

						num++;

					}

					return num;

				}

			}else{

				throw new RuntimeException("存储过程: "+proc+"无法通过正则表达式获取参数个数:\n"+code);

				

			}

		}

		rs.close();

		stmt.close();

		throw new RuntimeException("没有该存储过程");

		

	}

	/**

	 * 注意, 在存储过程的参数中,不能写注释,特别是 in xxx, 格式的注释,不然会被错误的识别

	 * @param con JDBC连接, 且不在函数内释放资源

	 * @param proc 调用的存储过程

	 * @param args 传递给存储过程的参数

	 * @throws 解析失败

	 * */

	public static int getProcedureArgsNumber(Connection con,String proc) throws Exception {

		if(con == null || proc == null|| proc.equals("")){

			throw new RuntimeException("proc, con 参数不能为空");

		}

		//这里可以做缓存

		return doWork(con,proc);

	}

	public static void main(String arg[]) throws Exception{

		



		Connection con = null; //表示数据库的连接对象  

		Class.forName("com.mysql.jdbc.Driver"); //1、使用CLASS 类加载驱动程序  

		con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8","root","root"); //2、连接数据库

		System.out.println(getProcedureArgsNumber(con,"my_procedure"));

		con.close();

	}



}


    

  该代码对存储过程的感知,是利用正则表达式的,所以在匹配的时候,可能遇到一些极端的情况,如 注释中包含了符合规则的 语句,不过一般来说,这种情况极少发生。

Java 感知Mysql存储过程变量数量


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论