This topic describes how to use Rust and OceanBase Cloud to build an application that can perform basic operations such as table creation, data insertion, and data query.
Prerequisites
- You have installed the Rust toolchain (rustup) and Cargo.
- You have registered an OceanBase Cloud account and created an instance and a MySQL-compatible tenant. For more information, see Create an instance and Create a tenant.
Procedure
- Check the versions of Rust and Cargo.
- Install the required dependencies.
- Obtain the connection information of OceanBase Cloud.
- Modify the database connection information in the
config.rsfile. - Run the
main.rsfile. - Perform the required 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 the required dependencies
Create a new Rust project:
cargo new oceanbase_demo cd oceanbase_demoUse
cargoto install themysqlcrate:cargo add mysql(Optional) If you need to use asynchronous operations, you can install the
mysql_asynccrate:cargo add mysql_async
Step 3: Obtain the connection information of OceanBase Cloud
Log in to the OceanBase Cloud console. In the instance list, expand the information of the target instance, and select Connect > Get Connection String under the target tenant.
For more information, see Obtain the connection string.
Fill in the corresponding information in the URL based on the 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 for accessing 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 example shows how to add the complete code to the
main.rsfile: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 runThe 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
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 permission-related errors, make sure that the user has sufficient permissions to perform the required operations.
SQL syntax error: If there is a syntax error in the SQL statement, check whether the SQL statement is correctly formatted.
Data type error: If the data type of the inserted data does not match the table definition, make sure that the data type is correct.
Performance optimization recommendations
- Use a connection pool to manage database connections.
- Use asynchronous operations to improve concurrency performance.
- Use batch operations to improve data insertion efficiency.
- Set the database connection timeout time appropriately.