SQL语句为什么是错误的,而且房间没有报错?

huangapple go评论56阅读模式
英文:

Why the sql statement is wrong and the room does not report an error

问题

我现在知道SQL语句不能将列名作为参数。但为什么Room没有报错,仍然成功查询结果。只是它们不是按id倒序排列,而是按顺序排列。

日志输出也是正确的SQL语句。
```kotlin
// AppDatabase
Room.databaseBuilder(...).setQueryCallback({ sqlQuery, bindArgs ->
                Log.d("Android Room", "SQL Query: $sqlQuery SQL Args: $bindArgs")
            }, 
...

// logcat
SQL Query: SELECT * FROM ( SELECT * FROM t_user ORDER BY ? DESC ) LIMIT 60 OFFSET 0 SQL Args: [id]

你能告诉我Room如何处理这个SQL语句吗?


<details>
<summary>英文:</summary>

Dao

@Query("SELECT * FROM t_user ORDER BY :order DESC")
fun pagingSource(order: String): PagingSource<Int, User>

I now know that sql statements cannot take columnName as a parameter. But why Room didn&#39;t report an error, still succeeded in querying the results.It&#39;s just that they are not arranged in reverse order according to id, but in order.

The log print is also the correct sql statement.
```kotlin
// AppDatabase
Room.databaseBuilder(...).setQueryCallback({ sqlQuery, bindArgs -&gt;
                Log.d(&quot;Android Room&quot;, &quot;SQL Query: $sqlQuery SQL Args: $bindArgs&quot;)
            }, 
...

// logcat
SQL Query: SELECT * FROM ( SELECT * FROM t_user ORDER BY ? DESC ) LIMIT 60 OFFSET 0 SQL Args: [id]

Can you tell me how Room handles this sql statement?

答案1

得分: 1

正确,但在您的情况下,参数不被解释为列名,而被解释为一个字面字符串,就像'id'一样。由于字面字符串和表达式在ORDER BY子句中是有效且被接受的,因此您的查询被解析和解释为:

select * from t_user order by 'id';

这在语法上是错误的,但当然不会执行所期望的排序。详见演示

英文:

> I now know that sql statements cannot take columnName as a parameter

Correct, but in your case the parameter is not interpreted as the name of a column, but as a literal string, like &#39;id&#39; and since literal strings and expressions are valid and accepted in the ORDER BY clause, your query is parsed and interpreted as:

select * from t_user order by &#39;id&#39;;

which is not syntactically wrong, but of course does not perform the desired ordering.<br/>

See the demo.<br/>

huangapple
  • 本文由 发表于 2023年2月8日 15:44:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75382663.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定