如何SELECT * FROM table
不指定记录类型,然后遍历结果(未加载到内存中,我们的表很大)?
我需要的是逐行迭代,同时将每一行转换为JSON
。
我基本上想做这样的事情:
var selectRet = testdb->select("SELECT * FROM some_table", ());
.
.
.
foreach row in tb { io:println(<json> row);}
在研究了`ballerina.io文档一周之后,如果没有先使用类型行记录{.....}指定确切的ROW结构,我仍然无法完成此操作,这在您的表有200个时非常不便列。
谢谢
答案 0 :(得分:1)
理想情况下,转换为json不应将整个表加载到内存中。但是由于这个known issue服务器在表到json转换期间变为OOM。该修补程序将在即将发布的版本中提供。
您的用例是否在迭代表并将每行转换为json?如果是这样,一旦上述问题得到解决,您就可以按照以下步骤进行操作,而不会占用过多的内存。
import ballerina/io;
import ballerina/mysql;
endpoint mysql:Client testDB {
host: "localhost",
port: 3306,
name: "testdb",
username: "root",
password: "123",
poolOptions: { maximumPoolSize: 5 },
dbOptions: { useSSL: false }
};
function main(string... args) {
var selectRet = testDB->select("SELECT * FROM employee", ());
table dt;
match selectRet {
table tableReturned => dt = tableReturned;
error err => io:println("Select data from the table failed: "
+ err.message);
}
var ret = <json>dt;
json jsonData;
match ret {
json j => jsonData = j;
error e => io:println("Error occurred while converting the table to json" + e.message);
}
foreach j in jsonData {
match j {
string js => {
io:println("string value: ", js);
}
json jx => {
io:println("non-string value: ", jx);
}
}
}
}
答案 1 :(得分:0)
您可以将select查询返回的表转换为JSON,而无需将表转换为记录数组。看下面的示例。我用0.90.1的最新版本的Ballerina进行了尝试。我在这里使用了示例雇员数据库。
// This function returns an optional type 'error?'
function performSelect() returns error? {
endpoint mysql:Client testDB {
host: "localhost",
port: 3306,
name: "employees",
username: "root",
password: "root12345678",
poolOptions: { maximumPoolSize: 5 },
dbOptions: { useSSL: false, allowPublicKeyRetrieval:true, serverTimezone:"UTC" }
};
// If the select query results in an error,
// then the 'check' operator returns it to the caller of this function
table resultTable = check testDB->select("SELECT * FROM employees", ());
// convert the table to a json object
json resultJson = check <json>resultTable;
io:println(resultJson);
testDB.stop();
// Return nil since there are no errors occurred
return ();
}