What is the difference between related SQLite data-types like INT, INTEGER, SMALLINT and TINYINT?

前端 未结 5 1633
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 06:15

When creating a table in SQLite3, I get confused when confronted with all the possible datatypes which imply similar contents, so could anyone tell me the difference between

5条回答
  •  猫巷女王i
    2020-12-02 06:33

    As an addition to answer from dan04, if you want to blindly insert a NUMERIC other than zero represented by a TEXT but ensure that text is convertible to a numeric:

    your_numeric_col NUMERIC CHECK(abs(your_numeric_col) <> 0)
    

    Typical use case is in a query from a program that treats all data as text (for uniformity & simplicity, since SQLite already does so). The nice thing about this is that it allows constructs like this:

    INSERT INTO table (..., your_numeric_column, ...) VALUES (..., some_string, ...)
    

    which is convenient in case you're using placeholders because you don't have to handle such non-zero numeric fields specially. An example using Python's sqlite3 module would be,

    conn_or_cursor.execute(
        "INSERT INTO table VALUES (" + ",".join("?" * num_values) + ")",   
        str_value_tuple)  # no need to convert some from str to int/float
    

    In the above example, all values in str_value_tuple will be escaped and quoted as strings when passed to SQlite. However, since we're not checking explicitly the type via TYPEOF but only convertibility to type, it will still work as desired (i.e., SQLite will either store it as a numeric or fail otherwise).

提交回复
热议问题