面试题答案
一键面试use std::sync::Arc;
use tokio::sync::Mutex;
use futures::future::BoxFuture;
use tokio_postgres::{Client, Config, NoTls};
// 定义DatabaseConnection结构体
struct DatabaseConnection {
client: Option<Client>,
connected: bool,
}
impl DatabaseConnection {
// 初始化连接
async fn new() -> Result<Self, tokio_postgres::Error> {
let config = Config::new()
.user("your_username")
.password("your_password")
.host("localhost")
.port(5432)
.dbname("your_database");
let (client, connection) = config.connect(NoTls).await?;
tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("Database connection error: {}", e);
}
});
Ok(Self {
client: Some(client),
connected: true,
})
}
// 异步查询方法
async fn query(&mut self, sql: &str) -> Result<Vec<tokio_postgres::Row>, tokio_postgres::Error> {
if let Some(ref mut client) = self.client {
client.query(sql, &[]).await
} else {
Err(tokio_postgres::Error::Db("Not connected".to_string()))
}
}
}
// 异步运行时
#[tokio::main]
async fn main() {
let mut db = DatabaseConnection::new().await.expect("Failed to connect to database");
let result = db.query("SELECT * FROM your_table").await;
match result {
Ok(rows) => {
for row in rows {
println!("{:?}", row);
}
},
Err(e) => eprintln!("Query error: {}", e),
}
}
上述代码以Rust语言为例,实现了一个管理数据库连接的结构体DatabaseConnection
以及一个异步查询方法query
。这里使用tokio_postgres
库来处理PostgreSQL数据库连接。
- 结构体定义:
DatabaseConnection
结构体包含client
字段用于保存数据库客户端实例,connected
字段用于标识连接状态。 - 初始化连接:
new
方法负责初始化数据库连接,并将连接的生命周期通过tokio::spawn
进行妥善管理,避免在异步操作中提前释放。 - 异步查询:
query
方法确保在执行查询时,数据库连接是有效的,若连接存在则执行查询并返回结果。 - 异步运行时:使用
tokio::main
作为异步运行时入口,在main
函数中初始化数据库连接并执行查询操作。
如果是其他语言,实现思路类似,但语法和具体库的使用会有所不同。例如在Python中可使用asyncpg
库来处理异步PostgreSQL连接:
import asyncio
import asyncpg
# 定义DatabaseConnection类
class DatabaseConnection:
def __init__(self):
self.client = None
self.connected = False
# 初始化连接
async def new(self):
try:
self.client = await asyncpg.connect(user='your_username', password='your_password', host='localhost', port=5432, database='your_database')
self.connected = True
except Exception as e:
print(f"Failed to connect to database: {e}")
# 异步查询方法
async def query(self, sql):
if self.connected and self.client:
return await self.client.fetch(sql)
else:
raise Exception("Not connected")
# 异步运行时
async def main():
db = DatabaseConnection()
await db.new()
try:
result = await db.query("SELECT * FROM your_table")
for row in result:
print(row)
except Exception as e:
print(f"Query error: {e}")
if __name__ == "__main__":
asyncio.run(main())
在Python代码中:
- 类定义:
DatabaseConnection
类包含client
和connected
属性。 - 初始化连接:
new
方法负责建立数据库连接。 - 异步查询:
query
方法在连接有效时执行查询并返回结果。 - 异步运行时:使用
asyncio.run
来运行异步main
函数,在main
函数中初始化连接并执行查询。