Conteúdo do Curso
Databases in Python
Databases in Python
Data Types
SQLite provides several data types, or storage classes, to define the kind of data that can be stored in a table. While SQLite is dynamically typed and doesn’t enforce strict data types, it recognizes five primary affinity types.
Creating a Table with Different Data Types
Here’s an example of creating a table that uses various SQLite data types:
SQLite allows you to store data of any type in any column, regardless of the declared type when the table was created (except for INTEGER PRIMARY KEY
columns). It also uses an approach that helps correctly interpret and store data, ensuring everything works smoothly and efficiently.
import sqlite3 conn = sqlite3.connect('example.db') cursor = conn.cursor() # Creating the table cursor.execute(''' CREATE TABLE IF NOT EXISTS example_table ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER ) ''') # Inserting different types of data into the `age` column cursor.execute("INSERT INTO example_table (name, age) VALUES ('Alice', 25)") # standard value cursor.execute("INSERT INTO example_table (name, age) VALUES ('Bob', 'Thirty')") # text value in `INTEGER` column cursor.execute("INSERT INTO example_table (name, age) VALUES ('Charlie', 30.5)") # float value in `INTEGER` column # Retrieving all records from the table cursor.execute("SELECT * FROM example_table") rows = cursor.fetchall() # Printing the results for row in rows: print(row) # Closing the database connection conn.close()
This example demonstrates how SQLite allows inserting different types of data into the same column, even if the column is declared as INTEGER
. For instance, in the age
column (declared as INTEGER
), the following data is inserted:
- An integer (
25
); - A text value (
'Thirty'
); - A float value (
30.5
).
SQLite does not restrict the types of data you can insert into a column, thanks to its dynamic typing system. This approach allows storing a variety of data types in a single column without errors.
Obrigado pelo seu feedback!