Search code examples
ballerinaballerina-swan-lake

Error `action invocation as an expression not allowed here` in ballerina


I tried to access a database table using the MySQL library of ballerina. I am getting action invocation as an expression not allowed here error. I have given the sample code below.

import ballerina/sql;
import ballerinax/mysql;

mysql:Client|sql:Error dbClient = new ("localhost", "root", "password", "db", 3306);

sql:ParameterizedQuery query = SELECT * FROM patient;

sql:ExecutionResult result = check dbClient->execute(query);

What I'm doing wrong here?


Solution

  • A module-level variable cannot be initialized with an action. Only expressions are allowed. Actions are also shown in the sequence diagram and where they are allowed is more restricted than expressions. Moving it to a function will work, including the init function.

    import ballerina/sql;
    import ballerinax/mysql;
    
    mysql:Client dbClient = check new ("localhost", "root", "password","db", 3306); // changed
    sql:ExecutionResult result;
    
    function init() returns error? {
        sql:ParameterizedQuery query = `SELECT * FROM patient`;
        result = check dbClient->execute(query);
    }