Wednesday, May 29, 2019

Working with Postgresql database using Ballerina

  1. First, install Postgresql database.
  2. Download the postgresql driver jar and copy the Postgresql JDBC driver jar into $BALLERINA_HOME/bre/lib.
  3. Connect to your postgresql server and create a database:

  4. postgres=# create database testdb;
Sample

This is the sample to create a table using the Ballerina jdbc client, then insert a BIT data type record to the table.

Ballerina version used: 0.992.0

import ballerinax/jdbc;
import ballerina/io;
import ballerina/sql;
jdbc:Client testDB = new({
url: "jdbc:postgresql://localhost:13800/testdb",
username: "postgres",
password: "docker",
poolOptions: { maximumPoolSize: 5 }
});
public function main(string... args) {
var ret = testDB->update("CREATE TABLE BitTypes(ID SERIAL, bit_val BIT VARYING(64));");
handleUpdate(ret, "Create BitTypes table");
var insertRet = testDB->update("INSERT INTO BitTypes(bit_val) VALUES(B'101')");
handleUpdate(insertRet, "Update BitTypes table");
}
function handleUpdate(sql:UpdateResult|error returned, string message) {
if (returned is sql:UpdateResult) {
io:println(message + " status: " + returned.updatedRowCount);
} else {
io:println(message + " failed: " + <string>returned.detail().message);
}
}

Running the sample:

ballerina run workingWithBitDataPostgresql.bal

Output:

Create BitTypes table status: 0
Update BitTypes table status: 1

No comments:

Post a Comment