WSO2 Ballerina MySQL sample GET request
Ballerina version 1.0.0
Copy mysql-connector jar to home folder
- i.e. /Library/Ballerina/ballerina-1.0.0/distributions/jballerina-1.0.0/bre/lib
Create local database call testdb and it has an Account table with columns idAccount, Name, Amount.
sql_service.bal
import ballerina/io;
import ballerina/jsonutils;
import ballerinax/java.jdbc;
import ballerina/http;
jdbc:Client testDB = new({
url: "jdbc:mysql://localhost:3306/testdb",
username: "root",
password: "cioroot",
poolOptions: { maximumPoolSize: 5 },
dbOptions: { useSSL: false }
});
type Account record {
string idAccount;
string Name;
string Amount;
};
# A service representing a network-accessible API
# bound to port `9090`.
service getsalesstats on new http:Listener(9090) {
# A resource respresenting an invokable API method
# accessible at `/getsalesstats/getLTVData`.
#
# + caller - the client invoking this resource
# + request - the inbound request
resource function getLTVData(http:Caller caller, http:Request request) {
io:println("\nThe select operation - Select data from a table");
var selectRet = testDB->select("SELECT * FROM Account", Account);
table<Account> dt;
if (selectRet is table<Account>) {
json jsonConversionRet = jsonutils:fromTable(selectRet);
io:print("JSON: ");
io:println(jsonConversionRet.toJsonString());
} else {
error err = selectRet;
io:println("Select data from Account table failed: ",
<string> err.detail()["message"]);
}
}
}
sql_service_client.bal
import ballerina/http;
import ballerina/io;
public function main() returns error? {
http:Client helloClient = new("http://localhost:9090/getsalesstats");
http:Response helloResp = check helloClient->get("/getLTVData");
io:println(check helloResp.getTextPayload());
}
First run the command - ballerina run sql_service.bal to start the service
Then invoke the service from the client - ballerina run sql_service_client.bal
This will print Account table data in the service terminal.
Comments
Post a Comment