Jsp & stored procedures - sql

I issue SP from Jsp, code is here:
sql = "EXEC REP_INVOICES ?,?";
java.sql.PreparedStatement ps = cox.prepareStatement(sql);
ps.setEscapeProcessing(true);
ps.setInt(1, cycle);
ps.setInt(2, zone);
ps.execute();
Procedure runs several seconds and fills a table. I want to know when it is over to make outputs. Is it possible?

I has been ages since I did java.
However, there is JDBC and SQL libraries.
I think you are using the first. Here is a link to execute().
http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html
I guess the main question is this statement modal? After the execute() does the java wait until the call is finished? I think so.
Have the stored procedure return a value. Check it. After that, you whole table should be populated.
The only other alternative is to do paging. Load only a few records in the table at a time. Should produce quicker response times.
Here is the definition from the manual on return values and how to get them from a SPROC call.
execute
boolean execute()
Executes the SQL statement in this PreparedStatement object, which may be any kind of SQL
statement. Some prepared statements return multiple results; the execute method handles these
complex statements as well as the simpler form of statements handled by the methods
executeQuery and executeUpdate.
The execute method returns a boolean to indicate the form of the first result. You must call
either the method getResultSet or getUpdateCount to retrieve the result; you must call
getMoreResults to move to any subsequent result(s).

Related

If we have out parameter in plsql procedure and return in function.Then why we use procedure instead of function?

If we have only Out parameter in our PLSQL procedure.Then can we use function instead of procedure as function is also able to return the value.
And if we still using procedure then we use this instead of function.
I hope I am able to convey the right question which I want to ask?
Some important difference between both are as following:
Function:
It can be called from the SQL statement (SELECT, UPDATE, DELETE)
Can return only one value
DML operations are not allowed in it
Best for selecting the value for some common complex logic.
Procedure:
It cannot be called from the SQL statement. You must need the PL/SQL block to call it.
Can return multiple values (OUT parameters)
All DML operations are allowed within procedures.
Best for doing some complex logic and updating the table data accordingly.
It depends on what the procedure does.
For example, if it (along with returning some value) uses DML operations (e.g. inserts rows into some table), then function can't do that - you'll have to use a procedure.
Procedure's drawback is that you can't use it in a SELECT statement, such as
select proc_name(out_param) from dual;
You'll have to use a function in such cases.
Also, OUT parameter has to be stored somewhere, and that's usually a locally declared variable, but that means that you need another PL/SQL block to call the procedure and see its result.
If everything your current procedure does is to find & return some value, then yes - a function might be a better choice.

Stored Procedure delete statement after return

So I'm tracking down a potential bug in a sync process I'm in charge of (written by someone else). When viewing one of the stored procedures that is being called, I noticed something peculiar. Based on my understanding of returns, anything after the return will not be returned. However, I am not positive if this is the case in SQL. Based on the chunk of SQL below, will the delete statement ever run? Or does the SP return information to signify whether rows were deleted (such as how many rows, whether it was successful, etc.)? I am assuming this is a bug in the SP, but want to confirm before taking action. Thanks in advance.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[DeleteSalesforce_Contacts]
AS
Return
Delete From dbo.Contacts Where IsDeleted = 1
GO
The documentation is pretty clear on this:
"Exits unconditionally from a query or procedure. RETURN is immediate
and complete and can be used at any point to exit from a procedure,
batch, or statement block. Statements that follow RETURN are not
executed."
The delete statement won't be executed.
The return statement takes an optional parameter, but to use a query as value you would need to use a select in parentheses. Example:
return (select top 1 id from SomeTable)
The delete would never happen when the proc is executed.
The only time a statement after the return is ever executed when a proc is run is if it was related to a goto process and the code was sent there and bypassed the return. This kind of code sometimes used to be written before Try Catch blocks were allowed in SQL Server to do something with errors.

When the sql query are executed by ORM with rails?

if I make a function :
def test
User.where(name: 'foo')
return 42
end
If I call test method the sql is not done.
So where method just construct the request but not execute it.
It's like that we can add where or others sql method like limit, order...etc
Apparently, each time, this method construct request sql but not execute it.
So where, in source code, SQL are execute? What trigger this?
I don't understand the current mechanism...

Confirm SQLbuilder query was successful in Yii

Firstly, I apologise if this is a really stupid question.
I had a question about dealing correctly with SQL statements within Yii. I'll make a small example code.
public function actionCreate($id) {
$cmd = Yii::app()->db->createCommand();
$cmd->insert('table_1',array(
'user_id'=> (int) $id,
),'id=:id', array(':id'=>$id));
}
What's the correct way to confirm this query worked? Is it try/catch blocks?
The reason I ask is that could fail if it's passed a bad parameter, but on a couple of tables I have DB constraints that could also result in a failure, so I wanted to try and make sure I handled everything properly rather than blanket handle them.
From official document
Executing SQL Statements Once a database connection is established, SQL statements can be executed using CDbCommand. One
creates a CDbCommand instance by calling
CDbConnection::createCommand() with the specified SQL statement:
$connection=Yii::app()->db; // assuming you have configured a "db" connection
// If not, you may explicitly create a connection:
// $connection=new CDbConnection($dsn,$username,$password);
$command=$connection->createCommand($sql);
// if needed, the SQL statement may be updated as follows:
// $command->text=$newSQL;
A SQL statement is executed via CDbCommand in one of the following two ways:
And here it is
execute(): performs a non-query SQL statement, such as INSERT, UPDATE
and DELETE. If successful, it returns the number of rows that are
affected by the execution.
Btw, insert() is a low level method that's used internally by Active Record (AR). Why don't you simply use AR instead
By Yii gii, you automatically get model for table_1, and you can find, insert, update, delete from that. Example:
$model = new Table1ModelName;
$model->user_id= $id;
$model->name= $user_name;
...
$model->save();
There still has many workarounds and interesting things which you would like to study about
Yii Working Active Record

Removing possibility of injecting dangerous SQL queries

There is a function having a parameter. The function internally invokes a stored procedure with the parameter. And clients can pass a string to the function through HTTP requests.
I'm trying to add a method to remove any possibilities of injecting dangerous SQL statement through the parameter. The method name is IsSQLParameterSafe() and it returns boolean values depending on the parameter. If the value is safe to execute, then the method will return true, otherwise it returns false.
In my case, the parameter doesn't have to have blanks so if there are any whitespaces, then it'll return false. Also, I'm going to limit the length of the input up to 64 because its the maximum length of the parameter.
Do you think that my idea will work? If not, can you suggest ideas?
Thanks
You can use a parameterized query even with stored procedures. This is the best way to deal with SQL injection risks. It's difficult to be more specific without knowing what language you're using, but in Java, for example, you'd use something similar to this:
String callStmt = "CALL PROC(?)";
PreparedStatement prepStmt = con.prepareStatement(callStmt);
prepStmt.setString(1, parameter);
ResultSet rs = prepStmt.executeQuery();
You might also be interested in the OWASP SQL Injection Prevention Cheat Sheet, which goes into more detail.
You won't need to worry, unless you are stitching the SQL together manually and then executing it with the EXEC command.
For example, this is a simple Stored Procedure:
CREATE PROCEDURE DeleteRecord
(
#name VARCHAR(64)
)
AS
BEGIN
DELETE FROM Records WHERE [Name] = #name
END
If you attempt to pass this string into the procedure...
name OR 1=1
...then the Procedure will Delete 0 records, because no one has this exact name.
Why doesn't it delete everything?
The Stored Procedure doesn't stitch the SQL together into a big string (you often see this sort of thing in tutorials for beginners in PHP). Instead, it passes the original SQL statement, then each parameter as a distinct argument. I don't know the technical details of how this works, but I know from experience that adding slashes and quotes and garbled characters will not break this query.
But...
If you are writing Dynamic SQL, and if you parameter represents a Table or Column name, then you need to be more careful. I would use a white list for that.
http://www.sommarskog.se/dynamic_sql.html