I have this weird problem. I have defined a column in a SQLite database as STRING but when I use it with integers prefixed by a + it automatically converts them to a proper integer:
sqlite> create table test (key STRING);
sqlite> insert into test values ('+1');
sqlite> insert into test values ("+2");
sqlite> select * from test;
1
2
As you can see the + sign is removed. On the other hand, if I quote the strings twice:
sqlite> delete from test;
sqlite> insert into test values ('"+3"');
sqlite> insert into test values ("'+4'");
"+3"
'+4'
… it works as expected but they are quoted. My primary problem is that I need to “double quote” all strings because I cannot guarantee that some string might look like an integer to the database and therefore be tampered with.
This is what I would like to know:
- Why does SQLite behave like this (and maybe other implementations)?
- Can I do something about it? (Without the double quoting?)
Just for reference, inserting the string '+test' works as expected:
sqlite> delete from test;
sqlite> insert into test values ('+t');
sqlite> select * from test;
+t
(answer without quotes – whiii!)
This is related to SQLite’s dynamic data typing. In particular,
STRINGis not a valid type, so SQLite defaults it toNUMERICaffinity. In fact, to quote from that page:You want to declare your column as
TEXT, notSTRING. That will fix it.