Let's create a simple SQLite database using Python and manage its data:
import sqlite3
# Connect to the database or create it if it doesn't exist
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Create a table called 'users' with columns 'id', 'name', and 'email'
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL);''')
# Insert data into the 'users' table
cursor.execute("INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com');")
conn.commit()
# Query data from the 'users' table
cursor.execute('SELECT * FROM users;')
result = cursor.fetchall()
for row in result:
print(row)
# Update a record in the 'users' table
cursor.execute("UPDATE users SET name = 'Jane Doe' WHERE id=1;")
conn.commit()
What causes it: Misspelling a variable or function name.
# Bad code example
connecion = sqlite3.connect('example.db')
Error message:
NameError: name 'connecion' is not defined
Solution: Correct the spelling of the variable or function name.
# Corrected code
conn = sqlite3.connect('example.db')
Why it happens: Python cannot find a variable or function with the specified name, because it is misspelled or not defined.
How to prevent it: Double-check your spelling and make sure you are using the correct names for variables and functions.
What causes it: Trying to perform an incompatible operation on different data types.
# Bad code example
cursor.execute("UPDATE users SET name = 123;")
Error message:
TypeError: not all arguments converted during string formatting
Solution: Use the appropriate data type for each column in SQL statements.
# Corrected code
cursor.execute("UPDATE users SET name = '123';")
Why it happens: Python tries to convert different data types to a common format, but fails because of an incompatible operation.
How to prevent it: Ensure that the data type you are using for each column in SQL statements is compatible with its expected data type in the database schema.
python
conn.close()
python
cursor.execute("BEGIN TRANSACTION;")
# Multiple SQL operations go here
cursor.execute("COMMIT;")
python
try:
# SQL operation that might raise an error
except Error as e:
print(e)