Examples
Elixir Database CRUD
Building a CRUD App
Elixir database CRUD with Ecto handles data operations.
Introduction to Ecto
Ecto is a database wrapper and query generator for Elixir. It provides a standard way to interact with databases and is an essential tool in the Elixir ecosystem. Ecto helps you define schemas, run queries, and manage database transactions effectively.
Setting Up Ecto
To get started with Ecto in your Elixir project, you need to add it to your dependencies. Open your mix.exs
file and add Ecto and a database adapter to the list of dependencies:
After adding the dependencies, run mix deps.get
to install them.
Creating a Schema
A schema in Ecto is a representation of a database table. To create a schema, use the mix ecto.gen.schema
task. For example, let's create a schema for a simple User
model:
This command generates a User
module with fields for name
and email
. The generated schema file will be located in the lib
directory and looks like this:
Performing CRUD Operations
Once you have your schema, you can perform CRUD operations. Below are examples of how to create, read, update, and delete records in the database.
Create
To insert a new record, use the Repo.insert/1
function:
Read
To retrieve data, use Repo.get/2
or Repo.all/1
:
Update
To update a record, first retrieve it, change the fields, and then call Repo.update/1
:
Delete
To delete a record, use the Repo.delete/1
function:
Conclusion
Using Ecto in Elixir projects enables effective database management through clear and concise CRUD operations. With Ecto, you can easily define schemas, perform queries, and handle transactions, making it an invaluable tool for developers working with databases in Elixir.
Examples
- Previous
- Authentication API
- Next
- Concurrent Tasks