向SQLite查询传递搜索参数失败,求助解决SQLiteException错误
搞定你的SQLite语法错误!
嘿,作为SQLite新手踩这个坑太正常啦!你遇到的SQLiteException: no such column: appdd错误,根源在于直接用字符串拼接参数时,没给字符串类型的条件值加引号,导致SQLite把你的参数applock当成了表的列名,而不是你要匹配的字符串内容。而且这种写法还藏着SQL注入的大风险,可不能在正式代码里这么用哦。
正确姿势:用参数化查询
这是处理动态SQL参数的标准做法,既避免语法错误,又能彻底防范SQL注入。给你两种常用的实现方式:
方式一:用?占位符配合rawQuery
public List<MaterialsModel> getLocationMaterials(String applock) { List<MaterialsModel> materialsList = new ArrayList<>(); // 用?代替动态参数,不要直接拼接 String selectQuery = "SELECT * FROM tbl_test WHERE locations = ?"; SQLiteDatabase db = this.getReadableDatabase(); // 第二个参数是占位符对应的参数数组,顺序要和?对应 Cursor cursor = db.rawQuery(selectQuery, new String[]{applock}); // 遍历Cursor填充数据 if (cursor.moveToFirst()) { do { MaterialsModel model = new MaterialsModel(); // 这里根据你的MaterialsModel字段,从Cursor读取数据 model.setId(cursor.getInt(cursor.getColumnIndex("id"))); model.setLocation(cursor.getString(cursor.getColumnIndex("locations"))); // 其他字段同理处理 materialsList.add(model); } while (cursor.moveToNext()); } // 记得关闭Cursor和数据库连接 cursor.close(); db.close(); return materialsList; }
方式二:用Android自带的query方法(更规范)
如果你用的是SQLiteOpenHelper,推荐用这种更面向Android的写法:
public List<MaterialsModel> getLocationMaterials(String applock) { List<MaterialsModel> materialsList = new ArrayList<>(); SQLiteDatabase db = this.getReadableDatabase(); // 定义查询条件和参数 String selection = "locations = ?"; String[] selectionArgs = {applock}; // 调用query方法构建查询 Cursor cursor = db.query( "tbl_test", // 要查询的表名 null, // 要返回的列,null表示所有列 selection, // WHERE子句 selectionArgs,// WHERE子句的参数 null, // GROUP BY子句 null, // HAVING子句 null // ORDER BY子句 ); // 同样遍历Cursor填充数据 if (cursor.moveToFirst()) { do { MaterialsModel model = new MaterialsModel(); // 填充model的各个字段 materialsList.add(model); } while (cursor.moveToNext()); } cursor.close(); db.close(); return materialsList; }
为啥原来的写法会报错?
你原来的代码"SELECT * FROM tbl_test WHERE locations = "+ applock,假设applock的值是"Shanghai",拼接后的SQL会变成:
SELECT * FROM tbl_test WHERE locations = Shanghai
SQLite看到Shanghai没加引号,就会把它当成一个列名来查找,而你的表根本没有叫Shanghai的列,自然就抛出no such column的错误了。就算你手动加引号,比如改成"SELECT * FROM tbl_test WHERE locations = '"+ applock + "'",如果参数里包含单引号(比如用户输入O'Conner),又会导致SQL语法错误,还可能被坏人利用SQL注入攻击你的数据库,所以这种写法绝对不能用!
内容的提问来源于stack exchange,提问作者Geoff
相关产品推荐
相关产品推荐

