Welcome to the introduction to databases! In this lesson, you'll learn about the fundamental concepts and importance of databases in software development.
Databases are organized collections of data that enable efficient and structured storage, retrieval, and manipulation. They serve as a backbone for many applications, ensuring consistency, durability, and scalability. Here's some essential terminology:
Let's create a simple database using SQLite, a popular lightweight relational database management system. First, ensure you have Python and the sqlite3
library installed:
pip install sqlite3
Next, write a script to interact with our database:
import sqlite3
# Create a connection object
conn = sqlite3.connect('example.db')
# Create a cursor object
c = conn.cursor()
# Create the table 'users'
c.execute('''CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')
# Insert data into 'users' table
c.execute("INSERT INTO users VALUES (1, 'John Doe', 'john@example.com')")
conn.commit()
# Query data from 'users' table
cursor = c.execute('SELECT * FROM users')
for row in cursor:
print(row)
# Close the connection
conn.close()
What causes it: Improper syntax or missing parentheses, commas, or semicolons.
c.execute("CREATE TABLE users ID INTEGER PRIMARY KEY, name TEXT, email TEXT") # Missing parentheses
Error message:
Traceback (most recent call last):
File "example.py", line 13, in <module>
c.execute("CREATE TABLE users ID INTEGER PRIMARY KEY, name TEXT, email TEXT")
sqlite3.OperationalError: near "ID": syntax error
Solution: Add missing parentheses.
c.execute("CREATE TABLE users (ID INTEGER PRIMARY KEY, name TEXT, email TEXT)")
What causes it: Referencing a non-existent variable or object.
print(conn.email) # Non-existent attribute
Error message:
Traceback (most recent call last):
File "example.py", line 26, in <module>
print(conn.email)
NameError: name 'conn' is not defined
Solution: Ensure you have created the connection object before referencing it.
conn = sqlite3.connect('example.db')
print(conn.name) # Corrected code
What causes it: Attempting to perform an operation on incompatible data types.
cursor = c.execute("SELECT id + name FROM users") # Incorrect arithmetic operation with text and integer data types
Error message:
Traceback (most recent call last):
File "example.py", line 30, in <module>
cursor = c.execute("SELECT id + name FROM users")
sqlite3.OperationalError: near "+": syntax error
Solution: Use the CAST()
function to convert data types before performing the operation.
cursor = c.execute("SELECT CAST(id AS TEXT) + name FROM users") # Corrected code
Now that you've learned the basics of databases, you can further explore advanced topics like SQL queries, database design, and performance optimization. Happy learning!