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
- Check the versions of Rust and Cargo.
- Install the required dependencies.
- Obtain the seekdb connection information.
- 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 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
-
Create a new Rust project:
cargo new seekdb_demo
cd seekdb_demo -
Use
cargoto install themysqlcrate:cargo add mysql -
(Optional) If you need to use asynchronous operations, install the
mysql_asynccrate: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.
-
Go to the
seekdb_demoproject folder. -
Add or modify the database connection information in the
main.rsfile.The following is a complete example of the code in 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
seekdb_demoproject directory:cd seekdb_demo -
Run 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 a permission-related error, ensure that the user has sufficient permissions to perform the required operations.
-
SQL syntax error: If the SQL statement has a syntax error, check whether the syntax of the SQL statement is correct.
-
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
- Use a connection pool to manage database connections.
- Use asynchronous operations to improve concurrent performance.
- Use batch operations to improve data insertion efficiency.
- Set the database connection timeout time appropriately.