英文:
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 0
s.<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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论