Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Update Operations | CRUD
Databases in Python

book
Update Operations

Update operations in SQLite involve modifying existing data in a database table. These operations are used to make changes to existing records based on specific criteria.

The primary SQL statement for updating data is the UPDATE statement. Here's a basic example:

python
import sqlite3

conn = sqlite3.connect("my_database.db") # connect to the database
cursor = conn.cursor()

# SQL query to update a specific record in the `articles` table
update_query = "UPDATE articles SET title = 'New Title' WHERE id = 1"
# Execute the SQL query to perform the update
cursor.execute(update_query)

conn.commit() # save the changes to the database
conn.close() # close the connection

This SQL query updates a record in the articles table, replacing the value of the title field with "New Title" for the record where the id is 1. Then, the command cursor.execute(update_query) sends the SQL query to the database, applying the changes to the specified record in the table.

Updating Multiple Records

To update multiple records that match certain criteria, you can use a WHERE clause in the UPDATE query:

sql
UPDATE articles SET title = "New Title" WHERE author = "John"

This query will update the "title" for all records where the author matches "John Doe".

Updating Multiple Columns

You can also update multiple columns simultaneously by specifying multiple column assignments in the SET clause:

sql
UPDATE articles SET title = "New Title", content = "New Content" WHERE id = 1

This query will update both the "title" and "content" for the record with "id" equal to 1.

f-Strings for Easy SQL Queries

Using f-strings in Python for writing SQL queries in the sqlite3 library is very convenient, as it allows you to dynamically integrate variable values without additional formatting operations. This simplifies both reading and writing code, as variables are embedded directly into the query text.

You can use variables in your UPDATE queries to update data dynamically.

python
new_title = "Updated Title"
record_id = 2
update_query = f"UPDATE articles SET title = '{new_title}' WHERE id = {record_id}"

This query will update the "title" of the record with "id" equal to the value stored in the record_id variable.

These are the basic concepts for performing update operations in SQLite using Python. You can customize your UPDATE queries to modify specific data in your database as needed.

Завдання

Swipe to start coding

Write an SQL query to update a user's email address in the users table. Change the value of the email field to 'new@gmail.com' for the record where the id is 1.

Рішення

import sqlite3

conn = sqlite3.connect('mydatabase.db') # create the database
cursor = conn.cursor()

# Create the `users` table with fields
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER, user_name TEXT, email TEXT, password TEXT)")

# Insert a record into the `users` table
cursor.execute("INSERT INTO users (id, user_name, email, password) VALUES (?, ?, ?, ?)", (1, "Alex", "AlexMain@gmail.com", "ZXCV2000"))

# Update the record
query = "UPDATE users SET email = 'new@gmail.com' WHERE id = 1"
cursor.execute(query)

# Execute select query
cursor.execute("SELECT * FROM users")

data = cursor.fetchall()
print(data)

conn.commit() # save changes
conn.close() # close the connection

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 4
import sqlite3

conn = sqlite3.connect('mydatabase.db') # create the database
cursor = conn.cursor()

# Create the `users` table with fields
cursor.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER, user_name TEXT, email TEXT, password TEXT)")

# Insert a record into the `users` table
cursor.execute("INSERT INTO users (id, user_name, email, password) VALUES (?, ?, ?, ?)", (1, "Alex", "AlexMain@gmail.com", "ZXCV2000"))

# Update the record
query = "___"
cursor.execute(query)

# Execute select query
cursor.execute("SELECT * FROM users")

data = cursor.fetchall()
print(data)

conn.commit() # save changes
conn.close() # close the connection

Запитати АІ

expand
ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

We use cookies to make your experience better!
some-alt