execSQL: is bindargs better?

北城以北 提交于 2019-12-23 02:35:05

问题


I was wondering in the execSQL method which can take 1 or 2 arguments.
Why using the second method, if I can use an object to directly do my operation on an SQLite db?

In example:

db.execSQL("INSERT INTO "+ TableName +" VALUES (null, ?)",
        new Object[] { type.getName() })

is this better than using this

db.execSQL("INSERT INTO "+ TableName +" VALUES (null,"+  type.getName() +")")

is the 1st example more secure?
faster when executing?
easier to read...
or is it the same?


回答1:


Method 1 is better.

It saves you from SQL injection, for instance.
Because it handles the datatypes for you.

Meaning that it converts the strings when needed by adding the string delimiters and converting the apostrophes.

I.e.:

To work correctly, you should write method 2 like

db.execSQL("INSERT INTO " + TableName + " VALUES (null, '" +  type.getName().replace("'", "''") + "')");

So...

is the 1st example more secure? Yes.
faster when executing? Not sure if it is.
easier to read Yes, once you get used to it (primarily opinion based).
... or is it the same? No, for what discussed above.



来源:https://stackoverflow.com/questions/34619601/execsql-is-bindargs-better

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!