· 8 years ago · Aug 12, 2018, 10:48 AM
1import ballerina/jdbc;
2import ballerina/io;
3import ballerina/mysql;
4
5endpoint mysql:Client testDB {
6 host: "localhost",
7 port: 3306,
8 name: "customerdb",
9 username: "root",
10 password: "123",
11 poolOptions: { maximumPoolSize: 5 },
12 dbOptions: { useSSL: false }
13};
14
15public type CustomerRecord record {
16 int id,
17 string name,
18};
19
20
21function main(string... args) {
22 // We first create connect to the database and create a database table
23 var ret = testDB->update("CREATE TABLE IF NOT EXISTS Customer (ID INT, NAME VARCHAR(30))");
24
25 match ret {
26 int retInt => io:println("Table creation status: " + retInt);
27 error err => io:println(err.message);
28 }
29
30 // Now let's obtain a 'proxy' table to the table we just created. Here you need to pass the name of the actual table,
31 // and the Ballerina record type that a row of the database table could be mapped with.
32 var proxyRet = testDB->getProxyTable("Customer", CustomerRecord);
33
34 table<CustomerRecord> tbProxy;
35 match proxyRet {
36 table tbReturned => tbProxy = tbReturned;
37 error err => io:println("Proxy table retrieval failed: " + err.message);
38 }
39
40 // Now we create a record and insert it to the database table through the proxy table we obtained.
41 CustomerRecord cr1 = { id: 1, name: "Tom" };
42 CustomerRecord cr2 = { id: 2, name: "Will" };
43 _ = tbProxy.add(cr1);
44 _ = tbProxy.add(cr2);
45
46 // Now let's iterate the database table through our proxy table.
47 foreach entry in tbProxy {
48 io:println(entry.id + "|" + entry.name);
49 }
50
51 testDB.stop();
52}