[파이썬] SQLAlchemy 데이터 삭제 (DELETE)

SQLAlchemy is a popular Python library for working with databases. It provides a powerful and flexible ORM (Object Relational Mapper) which allows developers to interact with databases using Python code. In this blog post, we will explore how to delete data from a database using SQLAlchemy.

Prerequisites

Before we begin, make sure you have the following dependencies installed:

Connecting to the Database

The first step is to establish a connection to the database. SQLAlchemy supports multiple database backends, so you need to provide the appropriate connection URL based on the database you’re using. Here’s an example of connecting to a SQLite database:

from sqlalchemy import create_engine

# Replace 'sqlite:///path/to/database.db' with your database URL
engine = create_engine('sqlite:///path/to/database.db')

# Create a connection
conn = engine.connect()

Make sure to replace 'sqlite:///path/to/database.db' with the actual path to your database file.

Deleting Data

Once you have established a connection, you can delete data from the database using SQLAlchemy’s delete() method. Let’s say we have a table called users with the following structure:

Column Type
id INTEGER
name VARCHAR(100)
email VARCHAR(100)

To delete a row from the users table based on a certain condition, you can use the delete() method in combination with the where() clause. Here’s an example:

from sqlalchemy import delete

# Delete users where the id is 1
delete_statement = delete(users_table).where(users_table.c.id == 1)

# Execute the delete statement
conn.execute(delete_statement)

In the above code, we first create a delete statement delete_statement that specifies the condition for deleting the row - in this case, where the id is 1. Then, we execute the delete statement using conn.execute(delete_statement) to actually delete the row from the database.

Make sure to replace users_table with the actual table object or table name in your database.

Committing Changes and Closing Connection

After deleting the data, it’s important to commit the changes to the database using conn.commit() to ensure the changes are permanently saved. Finally, don’t forget to close the database connection using conn.close().

# Commit changes
conn.commit()

# Close the connection
conn.close()

Conclusion

SQLAlchemy provides a convenient and efficient way to delete data from a database using Python. In this blog post, we discussed how to establish a connection to the database, create a delete statement, execute the delete statement, commit changes, and close the connection. With these techniques, you can easily manipulate data in your database with SQLAlchemy.

I hope you found this blog post helpful! If you have any questions or suggestions, please let me know in the comments below. Happy coding!