-2
我嘗試使用休耕避免類似查詢的SQL注入的Android SQLite的
Cursor cursor = sqLiteDatabase.rawQuery(
"SELECT * FROM "
+ TableInformation.TABLE_NAME
+ " LEFT OUTER JOIN "
+ FavouritesItems.TableInformation.TABLE_NAME
+ " ON "
+ FavouritesItems.TableInformation.TABLE_NAME + "." + FavouritesItems.TableInformation.FAVOURITE_ITEM_ID
+ " = "
+ TableInformation.TABLE_NAME + "." + TableInformation.ITEM_ID
+ " WHERE 1 = 1"
+ (itemSearch.getItemDescription().length() > 0 ? " AND " + TableInformation.ITEM_DESCRIPTION + " LIKE %" + "?" + "% " : "")
+ (itemSearch.getItemDescriptionEn().length() > 0 ? " AND " + TableInformation.ITEM_DESCRIPTION_EN + " LIKE '%" + "?" + "%' " : "")
, mySQLStatementStrings);
做一個搜索方法在我的SQLite數據庫,但是當我編譯它拋出休耕異常,因爲編譯器不能找到問題標記爲'%'%'
FATAL EXCEPTION: main
Process: com.shamisoft.myjewelaryshopproject, PID: 18398
java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
at android.database.sqlite.SQLiteProgram.bind(SQLiteProgram.java:212)
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:166)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
at com.shamisoft.myjewelaryshopproject.classes.Items.getItemsSearch2(Items.java:705)
at com.shamisoft.myjewelaryshopproject.classes.SearchItemCustomDialog$1.onClick(SearchItemCustomDialog.java:103)
at android.view.View.performClick(View.java:4781)
at android.view.View$PerformClick.run(View.java:19874)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
問題是如何避免SQL注入在這種情況下?
你必須添加'?'來顯示它添加參數的位置。你傳遞一個參數但沒有地方添加那些,因此它會拋出一個異常 – Zoe
?標記在這裏後像word (itemSearch.getItemDescription()。length()> 0?「AND」+ TableInformation.ITEM_DESCRIPTION +「LIKE%」+「?」+「%」:「」) –
現在我意識到不是問題。問題是形成不良的SQL查詢。 '> 0?'不是一個好的SQL查詢(或者對此有效的) – Zoe