嘿,你實際上不能把它稱爲查詢。你必須使它成爲一個可調用的語句並執行它。這是我一直在使用的代碼。它也需要參數,但如果你不需要,只需刪除它。這是爲我的項目設置定製的,但這會幫助你:
/**
* This method takes in a stored procedure along with its parameters and parameter type and creates a result set from them.
* @param storedProcedure
* @param parameters
* @param parameterType
* @return
* @throws SQLException
*/
public static ResultSet createRSFromStoredProc(String storedProcedure, ArrayList<String> parameters, ArrayList<String> parameterType) throws SQLException {
// Initializes variables that are used in the method.
Connection dbConnection = null;
CallableStatement callableStatement = null;
ResultSet rs = null;
// Builds the stored procedure calling
String insertStoreProc = "{call " + storedProcedure + "(";
for(int i=0;i<parameters.size(); i++)
{
if(i==parameters.size()-1)
insertStoreProc+="?";
else
insertStoreProc+="?,";
}
insertStoreProc+=")}";
try {
// establishes the connection
dbConnection = getDBConnection();
// creates the callable statement
callableStatement = dbConnection.prepareCall(insertStoreProc);
// Parses the string into the correct parameter type and sets the parameter to the value.
for(int i=0;i<parameters.size(); i++)
{
if(parameterType.get(i).equals("string"))
callableStatement.setString(i+1, parameters.get(i));
else if(parameterType.get(i).equals("int"))
callableStatement.setInt(i+1, Integer.parseInt(parameters.get(i)));
if(parameterType.get(i).equals("dateTime"))
{
// if now is entered for the time gets the current timestamp
if(parameters.get(i).equals("now"))
callableStatement.setTimestamp(i+1, Timestamp.valueOf(getCurrentDate()));
else
{
callableStatement.setString(i+1, parameters.get(i));
}
}
}
// execute insertDBUSER store procedure
Boolean results = callableStatement.execute();
int rowsAffected=0;
while(results||rowsAffected!=-1)
{
if(results)
{
rs=callableStatement.getResultSet();
break;
}
else
{
rowsAffected=callableStatement.getUpdateCount();
}
results= callableStatement.getMoreResults();
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return rs;
}
你爲什麼認爲,這段代碼沒有用? – dnuka
,因爲它當我sysout它時不會返回任何東西 – amirhtk