1. 程式人生 > >ballerina 學習二十九 資料庫操作

ballerina 學習二十九 資料庫操作

dockerfile:
mysql 資料庫的dockerfile,包含資料的初始化
FROM mysql/mysql-server:5.7
COPY inid.sql /docker-entrypoint-initdb.d
docker-compose.yaml: docker-compose 執行包含ballerina api 以及資料庫
version: "3"
services:
   api:
    image: dalongrong/mysql_demo:v1.0
    ports:
    - "9090:9090"
   mysql:
    build: ./
    ports:
      - 3306:3306
    command: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: EMPLOYEE_RECORDS
      MYSQL_USER: gogs
      MYSQL_PASSWORD: dalongrong
      TZ: Asia/Shanghai

inid.sql: 操作依賴的資料庫模型
/* 
 * MySQL Script - initializeDataBase.sql.
 * Create EMPLOYEE_RECORDS database and EMPLOYEES table.
 */

-- Create EMPLOYEE_RECORDS database
CREATE DATABASE IF NOT EXISTS EMPLOYEE_RECORDS;     

-- Switch to EMPLOYEE_RECORDS database
USE EMPLOYEE_RECORDS;

-- create EMPLOYEES table in the database
CREATE TABLE IF NOT EXISTS EMPLOYEES (EmployeeID INT, Name VARCHAR(50), Age INT, SSN INT, PRIMARY KEY (EmployeeID))

mysql_service.bal: 資料庫操作程式碼,集成了docker

import ballerina/config;
import ballerina/http;
import ballerina/log;
import ballerina/mysql;
import ballerina/sql;
import ballerinax/docker;

type Employee record {
    string name;
    int age;
    int ssn;
    int employeeId;
};

// Create SQL endpoint to MySQL database
endpoint mysql:Client employeeDB {
    host: "mysql",
    port: config:getAsInt("DATABASE_PORT", default = 3306),
    name: config:getAsString("DATABASE_NAME", default = "EMPLOYEE_RECORDS"),
    username: config:getAsString("DATABASE_USERNAME", default = "gogs"),
    password: config:getAsString("DATABASE_PASSWORD", default = "dalongrong"),
    dbOptions: { useSSL: false }
};
@docker:Config {
    registry: "dalongrong",
    name: "mysql_demo",
    tag: "v1.0"
}

@docker:CopyFiles {
  // 注意此處mysql jdbc 驅動地址,為了使用簡單,我寫的是絕對路徑,實際上構建之後會copy 到target 目錄,方便映象構建
    files: [{ source: "/Users/dalong/mylearning/ballerina-project/learning/guide/mysql_demo/mysql-connector-java-8.0.13.jar",
            target: "/ballerina/runtime/bre/lib" }]
}

@docker:Expose {}
endpoint http:Listener listener {,
    port: 9090
};

// Service for the employee data service
@http:ServiceConfig {
    basePath: "/records"
}
service<http:Service> EmployeeData bind listener {

    @http:ResourceConfig {
        methods: ["POST"],
        path: "/employee/"
    }
    addEmployeeResource(endpoint httpConnection, http:Request request) {
        // Initialize an empty http response message
        http:Response response;
        Employee employeeData;
        // Extract the data from the request payload
        var payloadJson = check request.getJsonPayload();
        employeeData = check <Employee>payloadJson;

        // Check for errors with JSON payload using
        if (employeeData.name == "" || employeeData.age == 0 || employeeData.ssn == 0 ||
            employeeData.employeeId == 0) {
            response.setTextPayload("Error : json payload should contain
             {name:<string>, age:<int>, ssn:<123456>,employeeId:<int>} ");
            response.statusCode = 400;
            _ = httpConnection->respond(response);
            done;
        }

        // Invoke insertData function to save data in the Mymysql database
        json ret = insertData(employeeData.name, employeeData.age, employeeData.ssn,
            employeeData.employeeId);
        // Send the response back to the client with the employee data
        response.setJsonPayload(ret);
        _ = httpConnection->respond(response);
    }

    @http:ResourceConfig {
        methods: ["GET"],
        path: "/employee/{employeeId}"
    }
    retrieveEmployeeResource(endpoint httpConnection, http:Request request, string
    employeeId) {
        // Initialize an empty http response message
        http:Response response;
        // Convert the employeeId string to integer
        int empID = check <int>employeeId;
        // Invoke retrieveById function to retrieve data from Mymysql database
        var employeeData = retrieveById(empID);
        // Send the response back to the client with the employee data
        response.setJsonPayload(untaint employeeData);
        _ = httpConnection->respond(response);
    }

    @http:ResourceConfig {
        methods: ["PUT"],
        path: "/employee/"
    }
    updateEmployeeResource(endpoint httpConnection, http:Request request) {
        // Initialize an empty http response message
        http:Response response;
        Employee employeeData;
        // Extract the data from the request payload
        var payloadJson = check request.getJsonPayload();
        employeeData = check <Employee>payloadJson;

        if (employeeData.name == "" || employeeData.age == 0 || employeeData.ssn == 0 ||
            employeeData.employeeId == 0) {
            response.setTextPayload("Error : json payload should contain
             {name:<string>, age:<int>, ssn:<123456>,employeeId:<int>} ");
            response.statusCode = 400;
            _ = httpConnection->respond(response);
            done;
        }

        // Invoke updateData function to update data in mysql database
        json ret = updateData(employeeData.name, employeeData.age, employeeData.ssn,
            employeeData.employeeId);
        // Send the response back to the client with the employee data
        response.setJsonPayload(ret);
        _ = httpConnection->respond(response);
    }

    @http:ResourceConfig {
        methods: ["DELETE"],
        path: "/employee/{employeeId}"
    }
    deleteEmployeeResource(endpoint httpConnection, http:Request request, string
    employeeId) {
        // Initialize an empty http response message
        http:Response response;
        // Convert the employeeId string to integer
        var empID = check <int>employeeId;
        var deleteStatus = deleteData(empID);
        // Send the response back to the client with the employee data
        response.setJsonPayload(deleteStatus);
        _ = httpConnection->respond(response);
    }
}

public function insertData(string name, int age, int ssn, int employeeId) returns (json){
    json updateStatus;
    string sqlString =
    "INSERT INTO EMPLOYEES (Name, Age, SSN, EmployeeID) VALUES (?,?,?,?)";
    // Insert data to SQL database by invoking update action
    var ret = employeeDB->update(sqlString, name, age, ssn, employeeId);
    // Use match operator to check the validity of the result from database
    match ret {
        int updateRowCount => {
            updateStatus = { "Status": "Data Inserted Successfully" };
        }
        error err => {
            updateStatus = { "Status": "Data Not Inserted", "Error": err.message };
        }
    }
    return updateStatus;
}

public function retrieveById(int employeeID) returns (json) {
    json jsonReturnValue;
    string sqlString = "SELECT * FROM EMPLOYEES WHERE EmployeeID = ?";
    // Retrieve employee data by invoking select action defined in ballerina sql client
    var ret = employeeDB->select(sqlString, (), employeeID);
    match ret {
        table dataTable => {
            // Convert the sql data table into JSON using type conversion
            jsonReturnValue = check <json>dataTable;
        }
        error err => {
            jsonReturnValue = { "Status": "Data Not Found", "Error": err.message };
        }
    }
    return jsonReturnValue;
}

public function updateData(string name, int age, int ssn, int employeeId) returns (json){
    json updateStatus = {};
    string sqlString =
    "UPDATE EMPLOYEES SET Name = ?, Age = ?, SSN = ? WHERE EmployeeID = ?";
    // Update existing data by invoking update action defined in ballerina sql client
    var ret = employeeDB->update(sqlString, name, age, ssn, employeeId);
    match ret {
        int updateRowCount => {
            if (updateRowCount > 0) {
                updateStatus = { "Status": "Data Updated Successfully" };
            }
            else {
                updateStatus = { "Status": "Data Not Updated" };
            }
        }
        error err => {
            updateStatus = { "Status": "Data Not Updated", "Error": err.message };
        }
    }
    return updateStatus;
}

public function deleteData(int employeeID) returns (json) {
    json updateStatus = {};

    string sqlString = "DELETE FROM EMPLOYEES WHERE EmployeeID = ?";
    // Delete existing data by invoking update action defined in ballerina sql client
    var ret = employeeDB->update(sqlString, employeeID);
    match ret {
        int updateRowCount => {
            updateStatus = { "Status": "Data Deleted Successfully" };
        }
        error err => {
            updateStatus = { "Status": "Data Not Deleted", "Error": err.message };
        }
    }
    return updateStatus;
}

相關推薦

ballerina 學習 資料庫操作

dockerfile: mysql 資料庫的dockerfile,包含資料的初始化 FROM mysql/mysql-server:5.7 COPY inid.sql /docker-entrypoint-initdb.d docker-compose.yaml: docker-compose 執

學習

linux學習七周三次課(3月21日)10.11 Linux網絡相關10.12 firewalld和netfilter10.13 netfilter5表5鏈介紹10.14 iptables語法 擴展(selinux了解即可) selinux教程 http://os.51cto.com/art/201209

ballerina 學習六 專案docker 部署&& 執行(

ballerina 從釋出,到現在官方文件的更新也是很給力的,同時也有好多改進,越來越好用了 可以參考官方文件 https://ballerina.io/learn/by-guide/restful-service/ 專案初始化 專案結構 └── guide └──

ballerina 學習七 專案k8s部署&& 執行

ballerina k8s 部署和docker 都是同樣的簡單,編寫service 添加註解就可以了 參考專案 https://ballerina.io/learn/by-guide/restful-service/ 專案準備 專案程式碼 import ballerina/h

【Katalon學習】測試套件和測試用例的設定/拆卸

測試套件和測試用例的設定/拆卸(5.3以上版本支援) 有關Katalon Studio中測試的完整生命週期,請參閱此文件。 現在,您的專案中的每個測試套件都具備了執行SetUp或Teardown方法的能力,這些方法是您自己在執行測試套件之前或之後定義的測試步驟組。這個特性是除了Test Li

ballerina 學習七 專案k8s部署&& 執行

import ballerina/http; import ballerinax/kubernetes; // 支援k8s 的註解 @kubernetes:Ingress { hostname:"dalongrong", name:"ballerina-guides-rest

ballerina 學習八 快速grpc 服務開發

ballerina 的grpc 開發模型,對於開發者來說簡單了好多,不是schema first 的方式,而是我們 只要編寫簡單的ballerina service 就可以了,proto 檔案是自動幫我們生成的,同時我們用這個 檔案方便的生成各種客戶端的程式碼 專案準備 專案結構

ballerina 學習六 專案docker 部署&& 執行(

ballerina 從釋出,到現在官方文件的更新也是很給力的,同時也有好多改進,越來越好用了 專案初始化 專案結構 └── guide └── restful_service └── order_mgt_service.bal 初始化專案

Salesforce LWC學習() getRecordNotifyChange(LDS拓展增強篇)

本篇參考: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/data_ui_api https://developer.salesforce.com/docs/component-library/docu

使用JdbcTemplate操作資料庫

使用JdbcTemplate操作資料庫 Spring的JdbcTemplate是自動配置的,你可以直接使用@Autowired來注入到你自己的bean中來使用。 舉例:我們在建立User表,包含屬性name、age,下面來編寫資料訪問物件和單元測試用例。 定義包含有插入、刪除、查詢的抽象介面Use

JAVA學習課(java程序的異常處理 ())

num 函數 錯誤 style col 編譯失敗 return [] java 異常處理的捕捉形式: 這是能夠對異常進行針對性處理的方式 六、try、catch的理解 詳細格式: try { //須要被檢測異常的代碼 } catch(異常類 變量)//改變量用

【轉】JMeter學習)使用Jmeter創建ActiveMQ JMS POINT TO POINT請求,環境搭建、請求創建、插件安裝、監聽服務器資源等

分布式 jndi 根目錄 point 啟動 lib .cn 轉載 p2p 最近要做公司消息中間件的性能測試,第一個想到的工具就是Jmeter了,網上簡單搜了一下,基本上都是WEB測試的居多,只好自己研究官方文檔了。 其中涉及Jmeter基本的術語或者概念,請自行參考官方文檔

Linux學習)iptables(三)nat表的應用

icmp cal 網卡 cast 默認值 ria bootproto cap span 需求 A機器可以訪問外網,B機器和A機器處於同一個內網,現在要讓B機器通過A機器訪問外網。 步驟 1.為虛擬機添加一塊網卡。 如果沒有區段名稱的話,點擊‘LAN區段(S)...’按鈕,

Linux學習筆記()日常運維一

日常運維一、查看系統負載w/uptime 查看系統負載 load average後指系統在一分鐘,五分鐘,十五分鐘內的運行狀態,平均有多少服務在運行負載值大於邏輯cpu數就說明超負荷了,數值小於cpu數是理想狀態 cat /proc/cpuinfo 查看cpu核數processor 後的數字就是cpu數量減一

Linux學習總結()系統日誌

log dmesg last xargs screen 系統日誌記錄了系統每天發生的各種各樣的事情,比如檢測系統狀況,檢測服務的啟動狀況,用戶的登陸情況等。我們可以通過日誌找出某個錯誤發生的原因,或者追蹤到攻擊者留下的蛛絲馬跡。 1 /var/log/messages 它是核心系統日誌文件

ElasticSearch學習筆記之 Java REST Client

ElasticSearch學習筆記之二十九 Java REST Client Java REST Client Java High Level REST Client Compatibility(相容性) Javadoc Maven Reposi

Meter學習)自動化badboy指令碼開發技術

一般人用badboy都是使用它的錄製功能,其它badboy還是一款自動化的工具,它可以實現檢查點、引數化、迭代、併發、報告、斷點等功能。本文就這些功能簡單介紹下。   環境準備: 下載地址:http://www.badboy.com.au/,下載後安裝即可。 工具:Badb

Effective_STL 學習筆記() 需要一個一個字元輸入時考慮使用 istreambuf_iterator

  使用 istreambuf_iterator : 1   ifstream inputFile( "interestingData.txt" ); 2   string fileData( (ifstreambuf_iterator<char>(inputFile)), i

opencv學習筆記:SIFT特徵點檢測與匹配

SIFT(Scale-invariant feature transform)是一種檢測區域性特徵的演算法,該演算法通過求一幅圖中的特徵點(interest points,or corner points)及其有關scale 和 orientation 的描述子得到特徵並進行

Python學習之旅(

Python基礎知識(28):常用第三方模組 一、Pillow PIL(Python Imaging Library):提供了強大的影象操作功能,可以通過簡單的程式碼完成複雜的影象處理,是Python平臺事實上的影象處理庫,支援Python 2.7以及更低的版本 Pillow:在PIL基礎上建立的相容版