为什么 Android 中的 SQLite 游标返回不同的值?

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

Why the sqlite cursor in android returns different values?

问题

我有一个简单的查询,你可以看到一行:

SELECT substr(..., 10, 6) as X

如果我使用 cursor.getInt(...),我得到 1048("错误" 值)

如果我使用 cursor.getString(...),我得到 "002030"(这是正确的)。

那么,是什么让 SQLite 将 "002030" 解析为 1048?

我是否需要每次都将其作为字符串获取并自己解析?

谢谢。

英文:

I have simple query, where you can see a row:

SELECT substr(..., 10, 6) as X

If I use cursor.getInt(...) I get 1048 (the "wrong" value)

If I use cursor.getString(...) I get "002030" (which is correct).

So, what makes sqlite parse "002030" as 1048?

Do I have to get it as string and parse it myself every time?

Thank you.

答案1

得分: 2

substr()函数返回一个字符串,所以你应该使用cursor.getString()来检索该值,它会返回正确的结果。

如果你希望结果是一个整数,你必须在你的SQL代码中进行转换,可以显式地这样做:

SELECT cast(substr(..., 10, 6) as integer) as X

或者隐式地这样做:

SELECT substr(..., 10, 6) + 0 as X

结果将是整数2030,没有前导的0

至于你得到的奇怪的1048,Java认为以0开头的数字文字是八进制数字,所以:

int x = 002030;

1048赋给了x,这是八进制数字2030的十进制表示。

英文:

The function substr() returns a string, so you should retrieve the value with cursor.getString(), which returns the correct result.<br/>

If you want the result as an integer, you must convert it in your sql code, either explicitly:

SELECT cast(substr(..., 10, 6) as integer) as X 

or implicitly:

SELECT substr(..., 10, 6) + 0 as X

The result will be the integer 2030 without the leading 0s.<br/>

As for the strange 1048 that you get, Java considers numeric literals starting with 0 as octal numbers, so:

int x = 002030;

assigns 1048 to x which is the decimal representation of the octal number 2030.

huangapple
  • 本文由 发表于 2020年9月28日 17:43:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/64099701.html
匿名

发表评论

匿名网友

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

确定