This topic describes how to build an application by using Rust and OceanBase Database. It also covers the use of the application for fundamental database operations such as creating tables, inserting data, and querying data.
Prerequisites
- You have installed the Rust toolchain (rustup) and Cargo.
- You have installed OceanBase Database V4.2.4 or later, and created a MySQL-compatible tenant.
Procedure
- Check the versions of Rust and Cargo.
- Install the necessary dependencies.
- Obtain the connection information of OceanBase Database.
- Modify the database connection information in the
config.rsfile. - Run the
main.rsfile. - Perform operations in the interactive CLI.
Step 1: Check the versions of Rust and Cargo
Open the terminal and run the following commands to check the versions of Rust and Cargo:
rustc --version
cargo --version
Step 2: Create a project and install the necessary dependencies
Create a new Rust project:
cargo new oceanbase_demo cd oceanbase_demoUse
cargoto install themysqlcrate:cargo add mysql(Optional) If asynchronous operations are needed, install the
mysql_asynccrate:cargo add mysql_async
Step 3: Obtain the connection information of OceanBase Database
Contact the deployment personnel or administrator of OceanBase Database 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 OceanBase Database. For connection through ODP, use the ODP address. For direct connection, use the IP address of the OBServer node.$port: the port for connecting to OceanBase Database. For connection through ODP, the default value is 2883. For direct connection, the default value is 2881.$database_name: the name of the database to be accessed.$user_name: the tenant account. For connection through ODP, the format isusername@tenant name#cluster nameorcluster name:tenant name:username. For direct connection, the format isusername@tenant name.$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.Add the following sample code to the
main.rsfile: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
Go to the
oceanbase_demoproject directory:cd oceanbase_demoRun the following command to start the program:
cargo runThe return 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 whether the following information is correct:
- Database address and port
- Username and password
- Network connection
Privilege error: If you encounter a privilege-related error, make sure that the user has sufficient privileges to perform the required operation.
SQL syntax error: If there is a syntax error in the SQL statement, check whether the syntax is correct.
Data type error: If the data type of the inserted data does not match that defined in the table, make sure that the data type is correct.
Performance optimization suggestions
- Manage database connections by using a connection pool.
- Use asynchronous operations to improve concurrency performance.
- Use batch processing to improve data insertion efficiency.
- Set a reasonable database connection timeout.