Android Question Why use parameterized commands

KMatle

Expert
Licensed User
Longtime User
Yep. If you create a full SQL query dynamically you build a string including the values. A value can contain anything. If a value contains valid SQL instructions, it will be added and then executed. This is called SQL injection.

It is essential to use prepared statements/parameterized commands. Here the SQL query is fixed, you use placeholders for the values which are then just values , no matter what they contain.
 
Upvote 0

MrKim

Well-Known Member
Licensed User
Longtime User
Worth watching this tutorial:


1. Safe from SQL injection.
2. Safe from escaping issues.
3. Easier to write and read.

I agree with everything but 3. Harder to write, especially harder to read.
 
Upvote 0

MrKim

Well-Known Member
Licensed User
Longtime User
I suppose one of the reasons is I have been doing code queries in VBA for a Looong time and am used to it. The example below, instead of looking at ? I am looking at fields with similar names by the equal signs so I know which one goes with which.. But an old dog can learn new tricks. I will give the parameters a try next time.

sql1.AddNonQueryToBatch("UPDATE JobRelease SET JobRelease.Jr_StartQty = " & Jr_StartQty & " WHERE (((JobRelease.Jr_JobNum) = '" & ClK.JobNum & "') And ((JobRelease.Jr_ReleaseNum) = " & ClK.Rel & "));", Null)

Is this how it would look with parameters? Or do I have to put the parameters in an array?

sql1.AddNonQueryToBatch("UPDATE JobRelease SET JobRelease.Jr_StartQty = ? WHERE (((JobRelease.Jr_JobNum) = ?) And ((JobRelease.Jr_ReleaseNum) = ?));", Jr_StartQty, ClK.JobNum, ClK.Rel)
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Please use [code]code here...[/code] tags when posting code.

It will look like this:
B4X:
sql1.AddNonQueryToBatch("UPDATE JobRelease SET JobRelease.Jr_StartQty = ? WHERE (((JobRelease.Jr_JobNum) = ?) And ((JobRelease.Jr_ReleaseNum) = ?));",Array(Jr_StartQty, ClK.JobNum, ClK.Rel))
- No need to add the apostrophes characters.
- No need to worry about any of the values including an apostrophe (which will break your code).
 
Upvote 0

MarkusR

Well-Known Member
Licensed User
Longtime User
at ms sql it will look like,if there is only one table used u do not need the tablename.
if you use "and" u not need brackets around
B4X:
sql1.AddNonQueryToBatch("UPDATE JobRelease SET Jr_StartQty = ? WHERE Jr_JobNum = ? And Jr_ReleaseNum = ?;",Array(Jr_StartQty, ClK.JobNum, ClK.Rel))
 
Last edited:
Upvote 0
Top