ballerinax/java.jdbc 错误无效的远程方法调用:需要一个客户端对象,但找到了

问题描述 投票:0回答:2

我正在尝试设置一个简单的 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;
}
sql visual-studio-code jdbc ballerina
2个回答
0
投票

这是因为 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


0
投票

如下更改隔离功能对我有用。我认为由于 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;
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.