Hope1234
Hope1234

Reputation: 13

Connecting to multiple database in robotframework using postgres

It is connecting only with first db , when trying to connect to db2 it is giving error as -: Setting 'Return' is allowed only once. Only the first value is used.

*** Keywords ***
Connect to Dbs
    [Arguments]  ${Db_Name}

    RUN KEYWORD IF    '${Db_Name}'=='db1'    
    ${connection} =  connect_to_postgres    connection details for db1
     Set Suite Variable     ${connection}
     [Return]  ${connection}

     ...    ELSE IF   '${Database_Name}'=='db2'
      ${connection} =  connect_to_postgres    connection details for db2
      Set Suite Variable     ${connection}
      [Return]  ${connection}

Execute SQL Queries
      [Arguments]     ${connection}    ${statement}
      @{query_results}=    execute_sql  ${connection}     ${statement}

Upvotes: 0

Views: 461

Answers (1)

Helio
Helio

Reputation: 3737

Like Pekka wrote in a comment, you only can have one [Return] statement in a keyword definition. In your case, you don't even need to return the connection, because you set it to be Suite Variable. Below I show three alternatives for you code:

Classic

*** Keywords ***
Connect to Dbs
    [Arguments]  ${Db_Name}
    [Return]  ${connection}
    ${connection} =    RUN KEYWORD IF    '${Db_Name}' == 'db1' 
   connect_to_postgres    connection details for db1
    ${connection} =    RUN KEYWORD IF    '${Database_Name}' == 'db2' 
   connect_to_postgres    connection details for db2
    Set Suite Variable     ${connection}

Execute SQL Queries
      [Arguments]     ${connection}    ${statement}
      @{query_results}=    execute_sql  ${connection}     ${statement}

Global

*** Keywords ***
Connect to Dbs
    [Arguments]  ${Db_Name}
    ${connection} =    RUN KEYWORD IF    '${Db_Name}' == 'db1' 
   connect_to_postgres    connection details for db1
    ${connection} =    RUN KEYWORD IF    '${Database_Name}' == 'db2' 
   connect_to_postgres    connection details for db2
    Set Suite Variable     ${connection}

Execute SQL Queries
      [Arguments]     ${statement}
      @{query_results}=    execute_sql  ${connection}     ${statement}

Modern

*** Keywords ***
Connect to Dbs
    [Arguments]  ${Db_Name}
    IF    '${Db_Name}' == 'db1' 
        ${connection} = connect_to_postgres    connection details for db1
    ELSE IF    '${Database_Name}' == 'db2' 
        ${connection} =    connect_to_postgres    connection details for db2
    END
    Return From Keyword   ${connection}    # [Return] would also work

Execute SQL Queries
      [Arguments]     ${connection}    ${statement}
      @{query_results}=    execute_sql  ${connection}     ${statement}

Upvotes: 1

Related Questions