文件首頁
X DevAPI 使用者指南
下載本手冊
PDF (美國信紙) - 1.4Mb
PDF (A4) - 1.4Mb


X DevAPI 使用者指南  /  使用結果集  /  使用資料集

9.3 使用資料集

擷取資料項目的作業會傳回一個游標,可用於從結果集使用這些資料項目。可以使用 Collection.find()Table.select()Session.sql() 從資料庫讀取資料項目。Collection.find() 會傳回一個包含文件的資料集,而 Table.select()Session.sql() 分別會傳回一個包含列的資料集。

所有結果集都實作了一種統一的方式來迭代其資料項目。統一語法支援使用 fetchOne() 一次擷取一個項目,或使用 fetchAll() 擷取所有項目的清單。fetchOne()fetchAll() 遵循僅限向前迭代語義。實作 X DevAPI 的連接器可以在頂端提供更進階的迭代模式,以符合常見的本機語言模式。

下列範例顯示如何使用 fetchOne() 迴圈處理所有文件來存取 Collection.find() 作業傳回的文件。

第一次呼叫 fetchOne() 會傳回找到的第一個文件。所有後續的呼叫都會將內部資料項目迭代器游標遞增一個位置,並傳回找到的項目,使得第二次呼叫 fetchOne() 會傳回找到的第二個文件 (如果有的話)。當最後一個資料項目已被讀取,且再次呼叫 fetchOne() 時,會傳回 NULL 值。這可確保顯示的基本 while 迴圈適用於所有支援此實作的語言。

使用 fetchOne() 時,無法將內部資料項目游標重設為第一個資料項目,以再次開始讀取資料項目。連接器可能會捨棄使用 fetchOne() 擷取一次的資料項目 (此處為文件)。資料項目的存留時間與資料集分離。從連接器的角度來看,項目會在呼叫者擷取它們時被使用。此範例假設測試綱要存在。

MySQL Shell JavaScript 程式碼

var myColl = db.getCollection('my_collection');

var res = myColl.find('name like :name').bind('name','L%').
        execute();

var doc;
while (doc = res.fetchOne()) {
  print(doc);
}

MySQL Shell Python 程式碼

myColl = db.get_collection('my_collection')

res = myColl.find('name like :name').bind('name','L%').execute()

doc = res.fetch_one()
while doc:
        print(doc)
        doc = res.fetch_one()

C# 程式碼

var myColl = db.GetCollection("my_collection");

var res = myColl.Find("name like :name").Bind("name", "L%")
  .Execute();

DbDoc doc;
while ((doc = res.FetchOne()) != null)
{
  Console.WriteLine(doc);
}

Python 程式碼

my_coll = db.get_collection('my_collection')

res = my_coll.find('name like :name').bind('name', 'L%').execute()

doc = res.fetch_one()
while doc:
    print(doc)
    doc = res.fetch_one()

Java 程式碼

Collection myColl = db.getCollection("my_collection");

DocResult res = myColl.find("name like :name").bind("name", "L%")
  .execute();

DbDoc doc;
while ((doc = res.fetchOne()) != null) {
  System.out.println(doc);
}

C++ 程式碼

Collection myColl = db.getCollection("my_collection");

DocResult res = myColl.find("name like :name").bind("name", "L%").execute();
DbDoc doc;
while ((doc = res.fetchOne()))
{
  cout << doc <<endl;
}

Node.js JavaScript 程式碼

var myColl = db.getCollection('my_collection');

myColl.find('name like :name')
  .bind('name', 'L%')
  .execute()
  .then(res => {
    while (doc = res.fetchOne()) {
      console.log(doc);
    }
  });


myColl.find('name like :name')
  .bind('name', 'L%')
  .execute(function (doc) {
    console.log(doc);
  });

使用 Node.js 時,也可以將結果傳回至回呼函數,每當伺服器傳回結果時,就會以非同步方式將結果傳遞至 execute()

var myColl = db.getCollection('my_collection');

myColl.find('name like :name')
  .bind('name', 'L%')
  .execute(function (doc) {
    console.log(doc);
});

下列範例顯示如何直接存取 Table.select() 作業傳回的列。結果迭代的基本程式碼模式相同。下列範例與前一個範例之間的差異在於資料項目處理。在此,fetchOne() 會傳回列。存取列的資料行值的確切語法取決於語言。實作會嘗試提供語言原生存取模式。此範例假設 test 綱要存在,且員工資料表存在於 myTable 中。

MySQL Shell JavaScript 程式碼

var myRows = myTable.select(['name', 'age']).
        where('name like :name').bind('name','L%').
        execute();

var row;
while (row = myRows.fetchOne()) {
  // Accessing the fields by array
  print('Name: ' + row['name'] + '\n');

  // Accessing the fields by dynamic attribute
  print(' Age: ' + row.age + '\n');
}

MySQL Shell Python 程式碼

myRows = myTable.select(['name', 'age']).where('name like :name').bind('name','L%').execute()

row = myRows.fetch_one()
while row:
        # Accessing the fields by array
        print('Name: %s\n' % row[0])
        # Accessing the fields by dynamic attribute
        print('Age: %s\n' % row.age)
        row = myRows.fetch_one()

Node.js JavaScript 程式碼

var myRows = myTable
  .select(['name', 'age'])
  .where('name like :name')
  .bind('name','L%')
  .execute(function (row) {
    // Connector/Node.js does not support referring to row columns by their name yet.
    // One needs to access fields by their array index.
    console.log('Name: ' + row[0]);
    console.log(' Age: ' + row[1]);
  });

或者,您可以使用回呼

myTable.select(['name', 'age'])
  .where('name like :name')
  .bind('name', 'L%')
  .execute()
  .then(myRows => {
    while (var row = myRows.fetchOne()) {
      // Accessing the fields by array
      console.log('Name: ' + row[0] + '\n');
      console.log('Age: ' + row[1] + '\n');
    }
  });

C# 程式碼

var myRows = myTable.Select("name", "age")
  .Where("name like :name").Bind("name", "L%")
  .Execute();

Row row;
while ((row = myRows.FetchOne()) != null)
{
  // Accessing the fields by array
  Console.WriteLine("Name: " + row[0]);

  // Accessing the fields by name
  Console.WriteLine("Age: " + row["age"]);
}

Python 程式碼

rows = my_table.select(['name', 'age']).where('name like :name').bind('name','L%').execute()

row = rows.fetch_one()
while row:
    # Accessing the fields by array
    print('Name: {0}'.format(row[0]))

    # Accessing the fields by dynamic attribute
    print('Age: {0}'.format(row['age'])

    row = rows.fetch_one()

Java 程式碼

RowResult myRows = myTable.select("name, age")
  .where("name like :name").bind("name", "L%")
  .execute();

Row row;
while ((row = myRows.fetchOne()) != null) {
  // Accessing the fields
  System.out.println(" Age: " + row.getInt("age") + "\n");
}

C++ 程式碼

RowResult myRows = myTable.select("name", "age")
                          .where("name like :name")
                          .bind("name", "L%")
                          .execute();

Row row;
while ((row = myRows.fetchOne()))
{
  // Connector/C++ does not support referring to row columns by their name yet.
  cout <<"Name: " << row[0] <<endl;
  cout <<" Age: " << row[1] <<endl;
  int age = row[1];
  // One needs explicit .get<int>() as otherwise operator<() is ambiguous
  bool uforty = row[age].get<int>() < 40;
  // Alternative formulation
  bool uforty = (int)row[age] < 40;
}