Skip to main content

Rust connection to seekdb sample program

This topic describes how to build an application that uses Rust and seekdb to perform basic operations such as creating tables, inserting data, and querying data.

Prerequisites

  • You have installed the Rust toolchain (rustup) and Cargo.
  • You have installed seekdb.

Procedure

  1. Check the versions of Rust and Cargo.
  2. Install the required dependencies.
  3. Obtain the seekdb connection information.
  4. Modify the database connection information in the config.rs file.
  5. Run the main.rs file.
  6. Perform the required operations in the interactive command-line interface.

Step 1: Check the versions of Rust and Cargo

Open a terminal and run the following command to check the versions of Rust and Cargo:

rustc --version
cargo --version

Step 2: Create a project and install the required dependencies

  1. Create a new Rust project:

    cargo new seekdb_demo
    cd seekdb_demo
  2. Use cargo to install the mysql crate:

    cargo add mysql
  3. (Optional) If you need to use asynchronous operations, install the mysql_async crate:

    cargo add mysql_async

Step 3: Obtain the seekdb connection information

Contact the seekdb deployment personnel or administrator to obtain the database connection string.

mysql -h$host -P$port -u$user_name -p$password -D$database_name

Parameter description:

  • $host: the IP address for connecting to seekdb. Replace it with the actual IP address. You can also use the local IP address 127.0.0.1.
  • $port: the port for connecting to seekdb. Replace it with the actual port number. The default value is 2881, which can be customized during the deployment of seekdb.
  • $database_name: the name of the database to be accessed.
  • $user_name: the username for the connection. Format: username.
  • $password: the password for the account.

Step 4: Modify the database connection information in the main.rs file

Modify the database connection information in the main.rs file based on the information obtained in Step 3.

  1. Go to the seekdb_demo project folder.

  2. Add or modify the database connection information in the main.rs file.

    The following is a complete example of the code in the main.rs file:

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

    fn main() -> Result<(), Box<dyn std::error::Error>> {
    const OCEANBASE_CONFIG: &str = "mysql://test_user001@mysql001:password@10.10.10.1:2881/test?charset=utf8mb4";

    // Establish connection
    println!("Connecting to database...");
    let pool = Pool::new(DB_URL)?;
    let mut conn = pool.get_conn()?;
    println!("Connected successfully!");

    // Create table
    conn.query_drop(
    r"CREATE TABLE IF NOT EXISTS users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )"
    )?;

    println!("Table created successfully!");

    // Insert sample data
    conn.exec_batch(
    r"INSERT INTO users (name, email) VALUES (?, ?)",
    vec![
    ("Alice", "alice@example.com"),
    ("Bob", "bob@example.com"),
    ("Charlie", "charlie@example.com"),
    ]
    )?;

    println!("Sample data inserted successfully!");

    // Query and display the data
    let selected_users = conn
    .query_map(
    "SELECT id, name, email FROM users",
    |(id, name, email)| {
    User { id, name, email }
    }
    )?;

    println!("\nCurrent users in database:");
    for user in selected_users {
    println!("ID: {}, Name: {}, Email: {}", user.id, user.name, user.email);
    }

    Ok(())
    }

    // Structure to hold user data
    struct User {
    id: i32,
    name: String,
    email: String,
    }

Step 5: Run the main.rs file

  1. Go to the seekdb_demo project directory:

    cd seekdb_demo
  2. Run the following command to start the program:

    cargo run

    The returned result is as follows:

    Connecting to database...
    Connected successfully!
    Table created successfully!
    Sample data inserted successfully!

    Current users in database:
    ID: 1, Name: Alice, Email: alice@example.com
    ID: 2, Name: Bob, Email: bob@example.com
    ID: 3, Name: Charlie, Email: charlie@example.com
    ID: 4, Name: Alice, Email: alice@example.com
    ID: 5, Name: Bob, Email: bob@example.com
    ID: 6, Name: Charlie, Email: charlie@example.com

FAQ

  1. Connection error: If you cannot connect to the database, check the following:

    • Whether the database address and port are correct
    • Whether the username and password are correct
    • Whether the network connection is normal
  2. Permission error: If you encounter a permission-related error, ensure that the user has sufficient permissions to perform the required operations.

  3. SQL syntax error: If the SQL statement has a syntax error, check whether the syntax of the SQL statement is correct.

  4. Data type error: If the data type of the inserted data does not match the table definition, ensure that the data type of the inserted data is correct.

Performance optimization recommendations

  1. Use a connection pool to manage database connections.
  2. Use asynchronous operations to improve concurrent performance.
  3. Use batch operations to improve data insertion efficiency.
  4. Set the database connection timeout time appropriately.