skip to Main Content

I have a SQL Server database table with this structure:

CREATE TABLE json_file_table 
(
    file_id VARCHAR(50) PRIMARY KEY,
    json_value VARBINARY(MAX)
);

How to write a SQL query to insert value into the database and bind values to that query in Ballerina?

2

Answers


  1. Assuming you are using NVARCHAR as the column type for json_value, you can use the toJsonString method to convert JSON to a string and store it as a string.

    public isolated function insertJSON(jdbc:Client dBCon, string fileId, json jsonValue) returns error? {
    
    sql:ParameterizedQuery insertQuery = `INSERT INTO json_file_table
                    ([file_id], [json_value])
                VALUES
                    (${fileId},${jsonValue.toJsonString()});`;
    any|error? result = dBCon->execute(insertQuery);
    

    }

    Login or Signup to reply.
  2. First you need to convert your json value into a byte[]

    json a = { "name": "John", "age": 30 };
    byte[] b = a.toString().toBytes();
    

    Then you needs to create a sql:varBinaryValue instance using above bytes.
    sql:VarBinaryValue varBinaryValue = new sql:VarBinaryValue(b).

    Then use that varBinaryValue in your sql query.

    import ballerina/sql;
    public function main() {
        json a = { "name": "John", "age": 30 };
        byte[] b = a.toString().toBytes();
        sql:VarBinaryValue varBinaryValue = new sql:VarBinaryValue(b);
    
        // use this varBinaryValue in a SQL query
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search