用rust连接MySQL数据库,并实现CRUD
时间: 2024-06-09 17:09:37 浏览: 194
连接MySQL数据库的rust库有很多,其中比较流行的有:
- mysql:https://crates.io/crates/mysql
- rust-mysql-simple:https://crates.io/crates/mysql-simple
这里以 `mysql` 库为例,演示如何连接MySQL数据库并实现CRUD操作。
首先,在 `Cargo.toml` 中添加依赖:
```toml
[dependencies]
mysql = "20.0.0"
```
然后,在代码中连接MySQL数据库:
```rust
use mysql::*;
fn main() -> Result<(), Box<dyn std::error::Error>> {
// 连接数据库
let url = "mysql://user:password@localhost:3306/mydb";
let pool = Pool::new(url)?;
let mut conn = pool.get_conn()?;
// 查询数据
let mut stmt = conn.prepare("SELECT id, name, age FROM users")?;
let result = stmt.execute(())?;
for row in result {
let (id, name, age) = from_row(row?);
println!("id: {}, name: {}, age: {}", id, name, age);
}
// 插入数据
let mut stmt = conn.prepare("INSERT INTO users (name, age) VALUES (?, ?)")?;
let result = stmt.execute(("Alice", 18))?;
println!("inserted rows: {}", result.affected_rows());
// 更新数据
let mut stmt = conn.prepare("UPDATE users SET age = ? WHERE name = ?")?;
let result = stmt.execute((19, "Alice"))?;
println!("updated rows: {}", result.affected_rows());
// 删除数据
let mut stmt = conn.prepare("DELETE FROM users WHERE name = ?")?;
let result = stmt.execute(("Alice",))?;
println!("deleted rows: {}", result.affected_rows());
Ok(())
}
```
这里的示例代码包括了查询、插入、更新和删除四种CRUD操作。其中,连接数据库的URL格式为 `mysql://user:password@host:port/database`,可以根据实际情况进行修改。在实际使用中,需要注意错误处理和连接池的使用等问题。
阅读全文