This topic describes how to build an application using Rust and OceanBase Cloud 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 registered an OceanBase Cloud account and created a cluster instance and a tenant in MySQL mode. For more information, see Create a cluster instance and Create a tenant.
Procedure
- Check the versions of Rust and Cargo.
- Install the necessary dependencies.
- Obtain the connection information for OceanBase Cloud.
- Modify the database connection information in the
main.rsfile. - Run the
main.rsfile. - Perform operations in the interactive command-line interface.
Step 1: Check the versions of Rust and Cargo
Open the 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 necessary dependencies
Create a new Rust project:
cargo new oceanbase_demo cd oceanbase_demoUse
cargoto install themysqlcrate:cargo add mysql(Optional) To use asynchronous operations, you can install the
mysql_asynccrate:cargo add mysql_async
Step 3: Obtain the connection information for OceanBase Cloud
Log in to the OceanBase Cloud console. On the instance list page, expand the target instance's information, and under the target tenant, select Connect > Get connection string.
For more detailed operations, see Get connection string.
Fill in the corresponding information in the URL below based on your created OceanBase Cloud database.
mysql -h$host -P$port -u$user_name -p$password -D$database_nameParameter description:
$host: The connection address of OceanBase Cloud, for example,t********.********.oceanbase.cloud.$port: The connection port of OceanBase Cloud. The default value is 3306.$database_name: The name of the database to be accessed.$user_name: The account used to access the database.$password: The password of 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.
Go to the
oceanbase_demoproject folder.Add or modify the database connection information in the
main.rsfile.The following is a complete sample code added to
main.rs:use mysql::*; use mysql::prelude::*; fn main() -> Result<(), Box<dyn std::error::Error>> { const OCEANBASE_CONFIG: &str = "mysql://`$user_name`:`$password`@$host:$port/$database_name?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
Go to the
oceanbase_demoproject directory:cd oceanbase_demoRun the following command to start the program:
cargo runExample output:
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
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.
Permission error: If you encounter a permission-related error, ensure the user has sufficient permissions to perform the required operation.
SQL syntax error: If an SQL statement contains a syntax error, check whether the SQL statement syntax is correct.
Data type error: If the data type of the inserted value does not match the table definition, ensure the inserted data type is correct.
Performance optimization suggestions
- Manage database connections using a connection pool.
- Improve concurrent performance by using asynchronous operations.
- Enhance data insertion efficiency through batch processing.
- Set an appropriate database connection timeout period.