以下是我的mysql存储过程,我在java代码中调用它。 我正在动态检查表名和限制值。它在mysql命令行内部工作。
问题是当我在java中调用此过程并尝试从结果集中读取时,它会给出无效的列异常。
`CREATE DEFINER=`root`@`localhost` PROCEDURE `top_gainers`(
IN sExchange VARCHAR (24),
IN iLimit INT,
OUT sStatus VARCHAR(10),
OUT sMessage VARCHAR(40)
)
BEGIN
SET sStatus = '0';
IF sExchange = '' OR iLimit = ''
THEN
SET sStatus = '1';
SET sMessage = 'Parameter is missing';
END IF;
SET @table_test = CONCAT('SHOW TABLES LIKE \'', sExchange,'\'');
PREPARE stmnt FROM @table_test;
EXECUTE stmnt;
DEALLOCATE PREPARE stmnt;
IF FOUND_ROWS() = 0
THEN
SET sStatus = '2';
SET sMessage = 'Invalid exchange selected';
END IF;
IF sStatus = '0'
THEN
SET @text = CONCAT('SELECT * FROM ', sExchange, ' ORDER BY CHANGE_PER DESC LIMIT ', iLimit);
PREPARE stmnt FROM @text;
EXECUTE stmnt;
DEALLOCATE PREPARE stmnt;
IF FOUND_ROWS() = 0
THEN
SET sStatus = '3';
SET sMessage = 'Could not find relevant data';
ELSE
SET sMessage = 'Market movers fetched successfully';
END IF;
END IF;
END`
这是java代码(我的表有SYMBOL和DESCRIPTION列):
conn = DBConnection.getInstance().getConnection();
String sQuery = "{CALL top_gainers(?, ?, ?, ?)}";
cstmt = conn.prepareCall(sQuery);
cstmt.setString(1, sExchange); // "NSE"
cstmt.setString(2, sLimit); // "10"
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR);
boolean hasResult = cstmt.execute();
JSONArray jArray = new JSONArray();
while (hasResult) {
ResultSet res = cstmt.getResultSet();
sStatus = cstmt.getString("sStatus");
sMessage = cstmt.getString("sMessage");
if (sStatus.equals("0")) {
while (res.next()) {
JSONObject jObj = new JSONObject();
jObj.put("symbol", res.getString("SYMBOL"));
jObj.put("description", res.getString("DESCRIPTION"));
jArray.put(jObj);
}
}
DBConnection.closeResultSet(res);
hasResult = cstmt.getMoreResults();
}
例外"专栏'符号'没找到。"
这是我的表:
+--------------------+---------------+------+-----+---------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+---------------+------+-----+---------------------+-------+
| SYMBOL | varchar(255) | NO | PRI | | |
| DESCRIPTION | varchar(255) | YES | | NULL | |
--------------------------------------------------------------------------------+
答案 0 :(得分:0)
发现了这个问题。我的程序返回了2个结果集,我试图访问列' SYMBOL'在第一个集合之上,只有表名(如果是有效的表名)
我在java代码中添加了以下行,并在访问值之前检查了列数。
ResultSetMetaData rsmd = res.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while(hasResult){ ResultSet res = cstmt.getResultSet();
ResultSetMetaData rsmd = res.getMetaData();
int columnsNumber = rsmd.getColumnCount();
sStatus = cstmt.getString("sStatus");
sMessage = cstmt.getString("sMessage");
if (columnsNumber > 1) {
while (res.next()) {
JSONObject jObj = new JSONObject();
jObj.put(APP_CONSTANT.SYMBOL, res.getString("SYMBOL"));
jObj.put(APP_CONSTANT.DESCRIPTION, res.getString("DESCRIPTION"));
jArray.put(jObj);
}
}
DBConnection.closeResultSet(res);
hasResult = cstmt.getMoreResults();
}