Rust code example to access MySQL

CK CK 3788 
Created at  
1,096 0 0

The mysql crate in Rust provides a client library for interacting with MySQL databases. It allows Rust programs to connect to MySQL servers, execute queries (both SQL and prepared statements), handle results, and manage transactions, all within a safe and idiomatic Rust environment. It offers features like connection pooling and asynchronous operations for improved performance and efficiency.

 

To access a MySQL server using Rust, you can use the mysql crate, which provides a simple and efficient interface for working with MySQL databases. Here's an example of how to connect to a MySQL server and execute a query:

 

Cargo.toml

First, add the mysql crate to your Cargo.toml:

[dependencies]
mysql = "23.1.0"  # Check for the latest version

 

Rust Code

Here's an example of a Rust program that connects to a MySQL server, executes a query, and prints the results:

use mysql::*;
use mysql::prelude::*;

fn main() -> Result<()> {
    // Define the database connection options
    let database_url = "mysql://username:password@localhost:3306/database_name";

    // Establish a connection to the database
    let pool = Pool::new(database_url)?;
    let mut conn = pool.get_conn()?;

    // Example: Create a table
    conn.query_drop(
        r"CREATE TABLE IF NOT EXISTS users (
            id INT PRIMARY KEY AUTO_INCREMENT,
            name VARCHAR(255) NOT NULL,
            age INT NOT NULL
        )",
    )?;

    // Example: Insert data
    conn.exec_drop(
        "INSERT INTO users (name, age) VALUES (:name, :age)",
        params! {
            "name" => "Alice",
            "age" => 30,
        },
    )?;

    // Example: Query data
    let selected_users: Vec<(u32, String, u32)> = conn.query("SELECT id, name, age FROM users")?;
    for user in selected_users {
        println!("ID: {}, Name: {}, Age: {}", user.0, user.1, user.2);
    }

    Ok(())
}

 

Explanation

  1. Database URL: Replace username, password, and database_name with your actual MySQL credentials and database name.
  2. Pool: Creates a pool of connections for efficient reuse.
  3. query_drop: Executes a query that doesn't return data, like CREATE TABLE or INSERT.
  4. query: Executes a query that returns data, like SELECT.

 

Running the Program

  1. Make sure your MySQL server is running and accessible.
  2. Replace the placeholder credentials in the code with actual values.
  3. Compile and run the program:

    cargo run
    

This example demonstrates basic CRUD operations. Depending on your use case, you can extend it further to handle more complex queries and error management.

Tags CRUD MySQL MySQL crate Rust MySQL Facebook X
Comments 0
Similar posts
  1. Using MySQL in Node.js
    474
  2. The Ultimate Data Engineering Roadmap
    1,069
  3. Change MySQL port number for security purpose
    815
  4. How do I create a user account in read-only mode at MySQL?
    3,267
  5. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  6. Stateful Databases: A Deep Dive with Cassandra & TiDB
    186
  7. How to set AUTO_INCREMENT ID in mySQL ?
    606
  1. How do I implement a heap in Rust?
    672
  2. How do I implement a stack in Rust?
    751
  3. Rust-GPU-tools for interacting with various GPU APIs
    753
  4. Rust array is fixed size. Can I modify its content?
    580
  5. Rust Example for Array and Dyamic Element Management (aka Vector-based Element Management)
    619
  6. The || syntax in Rust - also known as a closure
    599
  7. Basic Rust Thread Example to Perform Concurrent Computation
    611
  8. Multi-threaded HLS Server in Rust
    759
  9. Run a specific module in a external file with Rust
    567
  10. Question(?) Operator in Rust
    565
  11. Rust Documentation
    309
  12. Rust Compatibility
    714
  13. Rust Unsafe Operations
    356
  14. Rust Testing
    1,230
  15. Rust Std misc
    367
  16. Rust Std library types
    367
  17. Rust Error Handling
    339
  18. Rust Macro Rules
    1,496
  19. Rust mechanism for defining shared behavior across different types - Traits
    1,755
  20. Rust Scoping Rules - only accessible within the block of code
    1,059
  21. Rust Generics - Generalizing types and functionalities
    1,338
  22. Rust Attributes for conditional compilation, crate, lints, mark functions, macros
    309
  23. Rust Package Management Tool - cargo
    305
  24. Rust compilation unit - Crates
    249
  25. Rust Modules - Visivility, Struct Visibility, Use Declaration, super and self, File Hierarchy
    1,881
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    27
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    24
  3. How do I create animated background for Google Meet?
    19,711
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    217
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    85
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    153
  7. Array of arguments passed to script in PHP
    85
  8. Invalid Auction Storms in Ad Tech
    93
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    197
  10. The Two Clocks of Ad Server Architecture
    63
  11. Frequency Cap Architecture Overview
    509
  12. Collecting Proof-of-Play from 100,000 Screens
    141
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    280
  14. What is RedisVL?
    105
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    224
  16. TPU & GPU Cluster Management Tools
    232
  17. The Concept of Scaffolding in AI Agents
    221
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    575
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    252
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    326
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    197
  22. Machine Learning: Training vs. Ranking
    213
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    217
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    189
  25. Designing a Data Curation System Around a Vector Database
    215
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    229
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    649
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    185
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    207
  30. Understanding Data Lineage
    252