我正在尝试设置一个简单的 JDBC 客户端来与 Ballerina 中的数据库对话。
但是显示的“编译”(VSCode)错误说:
invalid remote method call: expected a client object, but found (ballerinax/java.jdbc:1.7.0:Client|ballerina/sql:1.7.1:Error)(BCE2421)
这是我的完整源代码:
import ballerinax/java.jdbc;
import ballerina/sql;
public type User record {|
int id?;
string name;
string username;
string email;
int? client_id;
|};
configurable string USER = ?;
configurable string PASSWORD = ?;
configurable string HOST = ?;
configurable int PORT = ?;
configurable string DATABASE = ?;
final jdbc:Client|sql:Error dbClient = new (
url="", user=USER, password=PASSWORD
);
isolated function getUser(int id) returns User|error {
sql:ParameterizedQuery query = `select * from users where ${id} = ?`;
User user = dbClient->query(query); // <--- THIS IS THE LINE THAT SHOWS ERROR
return user;
}
这是因为 Ballerina 错误处理与其他语言不同,有关错误处理的更多详细信息,请参阅Ballerina 示例:错误处理。
调查这个具体案例。当调用
getUser()
函数时,dbClient
可能是jdbc:Client
或sql:Error
。仅当变量为query()
类型时,您才能调用远程方法jdbc:Client
。在调用远程方法之前,您应该缩小 dbClient
的类型。
if dbClient is error {
// handle the error
} else {
// Type of `dbClient` will be `jdbc:Client` here.
sql:ExecutionResult result =
check dbClient->execute(`...`);
}
或者,您可以使用 check 关键字来缩小类型,因为
sql:Error
是 Ballerina 中的错误类型。
final jdbc:Client|sql:Error dbClient = check new (
url="", user=USER, password=PASSWORD
);
有关使用检查表达式处理错误的更多详细信息,请参阅Ballerina By Example: Check Expression。
如下更改隔离功能对我有用。我认为由于 ballerina 的错误处理,您应该返回错误以便保留所需的类型,否则您应该使用“检查”来做同样的事情。
isolated function getUser(int id) returns User|string {
sql:ParameterizedQuery query = `select * from users where ${id} = ?`;
jdbc:Client|sql:Error dbClient = new (
url = "", user = USER, password = PASSWORD
);
if (dbClient is sql:Error) {
return "Error occurred while retrieving user";
}
else if (dbClient is jdbc:Client) {
sql:ExecutionResult|sql:Error result = dbClient->execute(query);
if (result is sql:Error) {
return "Error occurred while retrieving user";
}
else if (result is sql:ExecutionResult) {
User user = {id, name: "", username: "", email: "", client_id: id};
// associate the result to the user record according to the result you retrieved from the database in the above line
return user;
}
}
}