sqlite3 ignoriert Datentypen und NOT NULL

Installation und Anwendung von Datenbankschnittstellen wie SQLite, PostgreSQL, MariaDB/MySQL, der DB-API 2.0 und sonstigen Datenbanksystemen.
Antworten
lackschuh
User
Beiträge: 281
Registriert: Dienstag 8. Mai 2012, 13:40

Hallo

Mir ist folgendes aufgefallen bzw unklar:

als Beispiel dient folgende Tabelle

Code: Alles auswählen

CREATE TABLE "test" ("id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL  UNIQUE , "test" TEXT NOT NULL , "testID" INTEGER NOT NULL )
Eigentlich sollte man nun in die Spalte "test" immer zwingend etwas reinschreiben und in die Spalte "testID" sollten nur Zahlen rein geschrieben werden dürfen. Komischerweise wird ein Datensatz auch dann geschrieben, wenn ich die Spalte "test" leer lasse und in die Splate "testID" Zeichen einfüge.

Kann mir jemand erklären, warum ich dann überhaupt noch Datentypen deklarieren muss, wenn diese sowieso ignoriert werden?

mfg
BlackJack

@lackschuh: Zum einen weil das nun mal zum SQL gehört. Dann weil SQLite die Typen durchaus bei den Rückgabewerten als Hinweis her nimmt als was der Wert interpretiert werden soll. Und SQLite entwickelt sich weiter — die Typen und Constraints könnten in einer zukünftigen Version geprüft werden.
EyDu
User
Beiträge: 4881
Registriert: Donnerstag 20. Juli 2006, 23:06
Wohnort: Berlin

http://www.sqlite.org/faq.html#q3 hat geschrieben:(3) SQLite lets me insert a string into a database column of type integer!

This is a feature, not a bug. SQLite uses dynamic typing. It does not enforce data type constraints. Any data can be inserted into any column. You can put arbitrary length strings into integer columns, floating point numbers in boolean columns, or dates in character columns. The datatype you assign to a column in the CREATE TABLE command does not restrict what data can be put into that column. Every column is able to hold an arbitrary length string. (There is one exception: Columns of type INTEGER PRIMARY KEY may only hold a 64-bit signed integer. An error will result if you try to put anything other than an integer into an INTEGER PRIMARY KEY column.)

But SQLite does use the declared type of a column as a hint that you prefer values in that format. So, for example, if a column is of type INTEGER and you try to insert a string into that column, SQLite will attempt to convert the string into an integer. If it can, it inserts the integer instead. If not, it inserts the string. This feature is called type affinity.
Das Leben ist wie ein Tennisball.
sma
User
Beiträge: 3018
Registriert: Montag 19. November 2007, 19:57
Wohnort: Kiel

Antworten