Create a new Rust project:
cargo new rust_mysql_crud
cd rust_mysql_crud
Add dependencies to Cargo.toml:
[dependencies]
actix-web = "4.0"
actix-rt = "2.8"
diesel = { version = "2.1", features = ["mysql"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
dotenv = "0.15"
Install Diesel CLI for migrations:
cargo install diesel_cli --no-default-features --features mysql
diesel setup
Configure the .env file: Create a .env file in your project root with the following content:
DATABASE_URL=mysql://username:password@localhost:3306/rust_mysql_crud
Generate a migration for the users table:
diesel migration generate create_users
Define the schema in migrations/_create_users/up.sql:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL
);
Run the migration:
diesel migration run
Run the Application Start the server:
cargo run