RussianLDP Рейтинг@Mail.ru
WebMoney: 
WMZ Z294115950220 
WMR R409981405661 
WME E134003968233 
Visa 
4274 3200 2453 6495 

Глава 6. Работа с относительными таблицами

Этот раздел объясняет, как использовать функции X DevAPI SQL CRUD, чтобы работать с относительными таблицами.

Следующий пример кода сравнивает операции, ранее показанные для коллекций и как они могут использоваться, чтобы работать с относительными таблицами, используя SQL. Упрощенный синтаксис X DevAPI продемонстрирован, используя SQL в сессии и то, как это подобно работе с документами.

MySQL Shell JavaScript Code

// Working with Relational Tables
var mysqlx = require('mysqlx');

// Connect to server using a connection URL
var mySession = mysqlx.getSession( {
  host: 'localhost', port: 33060,
  user: 'user', password: 'password'} )
var myDb = mySession.getSchema('test');

// Accessing an existing table
var myTable = myDb.getTable('my_table');
// Insert SQL Table data
myTable.insert(['name', 'birthday', 'age']).
        values('Laurie', mysqlx.dateValue(2000, 5, 27), 19).execute();

// Find a row in the SQL Table
var myResult = myTable.select(['_id', 'name', 'birthday']).
                       where('name like :name AND age < :age').
                       bind('name', 'L%').bind('age', 30).execute();
// Print result
print(myResult.fetchOne());

MySQL Shell Python Code

# Working with Relational Tables
from mysqlsh import mysqlx

# Connect to server using a connection URL
mySession = mysqlx.get_session( {
  'host': 'localhost', 'port': 33060,
  'user': 'user', 'password': 'password'} )

myDb = mySession.get_schema('test')
# Accessing an existing table
myTable = myDb.get_table('my_table')

# Insert SQL Table data
myTable.insert(['name','birthday','age']) \
  .values('Laurie', mysqlx.date_value(2000, 5, 27), 19).execute()

# Find a row in the SQL Table
myResult = myTable.select(['_id', 'name', 'birthday']) \
  .where('name like :name AND age < :age') \
  .bind('name', 'L%') \
  .bind('age', 30).execute()
# Print result
print(myResult.fetch_all())

Node.js JavaScript Code

// Working with Relational Tables
var mysqlx = require('@mysql/xdevapi');
var myTable;

// Connect to server using a connection URL
mysqlx
.getSession({
  user: 'user',
  password: 'password',
  host: 'localhost',
  port: 33060
})
.then(function (session) {
  // Accessing an existing table
  myTable = session.getSchema('test').getTable('my_table');
  // Insert SQL Table data
  return myTable
  .insert(['name', 'birthday', 'age'])
  .values(['Laurie', '2000-5-27', 19])
  .execute()
})
.then(function () {
  // Find a row in the SQL Table
  return myTable
  .select(['_id', 'name', 'birthday'])
  .where('name like :name && age < :age)')
  .bind('name', 'L%')
  .bind('age', 30)
  .execute(function (row) {
    console.log(row);
  });
})
.then(function (myResult) {
  console.log(myResult);
});

C# Code

// Working with Relational Tables

// Connect to server using a connection
var db = MySQLX.GetSession("server=localhost;port=33060;user=user;password=password")
.GetSchema("test");
// Accessing an existing table
var myTable = db.GetTable("my_table");

// Insert SQL Table data
myTable.Insert("name", "age")
.Values("Laurie", "19").Execute();

// Find a row in the SQL Table
var myResult = myTable.Select("_id, name, age")
.Where("name like :name AND age < :age")
.Bind(new { name = "L%", age = 30 }).Execute();

// Print result
PrintResult(myResult.FetchAll());

Python Code

# Working with Relational Tables
import mysqlx

# Connect to server using a connection URL
my_session = mysqlx.get_session({
  'host': 'localhost', 'port': 33060,
  'user': 'user', 'password': 'password'
})

my_schema = my_session.get_schema('test')
# Accessing an existing table
my_table = my_schema.get_table('my_table')

# Insert SQL Table data
my_table.insert(['name', 'birthday', 'age']) \
  .values('Laurie', mysqlx.date_value(2000, 5, 27), 19).execute()

# Find a row in the SQL Table
result = my_table.select(['_id', 'name', 'birthday']) \
  .where('name like :name AND age < :age') \
  .bind('name', 'L%') \
  .bind('age', 30).execute()

# Print result
print(result.fetch_all())

Java Code

// Working with Relational Tables
import com.mysql.cj.xdevapi.*;

// Connect to server using a connection URL
Session mySession = new SessionFactory().getSession("mysqlx://localhost:33060/test?user=user&password=password");
Schema db = mySession.getSchema("test");

// Accessing an existing table
Table myTable = db.getTable("my_table");
// Insert SQL Table data
myTable.insert("name", "birthday").values("Laurie", "2000-05-27").execute();

// Find a row in the SQL Table
RowResult myResult = myTable.select("_id, name, birthday")
  .where("name like :name AND age < :age")
  .bind("name", "L%").bind("age", 30).execute();
// Print result
System.out.println(myResult.fetchAll());

C++ Code

// Working with Relational Tables
#include <mysqlx/xdevapi.h>

// Connect to server using a connection URL
Session mySession(33060, "user", "password");
Schema myDb = mySession.getSchema("test");

// Accessing an existing table
Table myTable = myDb.getTable("my_table");
// Insert SQL Table data
myTable.insert("name", "birthday", "age").values("Laurie",
               "2000-5-27", 19).execute();

// Find a row in the SQL Table
RowResult myResult = myTable.select("_id", "name", "birthday")
  .where("name like :name AND age < :age")
  .bind("name", "L%").bind("age", 30).execute();

// Print result
Row row = myResult.fetchOne();
cout << " _id: " << row[0] << endl;
cout << "name: " << row[1] << endl;
cout << "birthday: " << row[2] << endl;

6.1. Функции SQL CRUD

Следующие функции CRUD SQL доступны в X DevAPI.

Table.insert()

Table.insert() используется, чтобы хранить данные в относительной таблице в базе данных. Это выполняется функцией execute().

Следующий пример показывает, как использовать Table.insert(). Пример предполагает, что испытательная схема существует и назначена на переменную db, и что существует пустая таблица my_table.

MySQL Shell JavaScript Code

// Accessing an existing table
var myTable = db.getTable('my_table');
// Insert a row of data.
myTable.insert(['id', 'name']).values(1,'Imani').values(2,'Adam').execute();

MySQL Shell Python Code

# Accessing an existing table
myTable = db.get_table('my_table')
# Insert a row of data.
myTable.insert(['id', 'name']).values(1, 'Imani').values(2, 'Adam').execute()

Node.js JavaScript Code

// Accessing an existing table
var myTable = db.getTable('my_table');
// Insert a row of data.
myTable.insert(['id', 'name']).values(1, 'Imani').values(2, 'Adam').execute();

C# Code

// Assumptions: test schema assigned to db, empty my_table table exists
// Accessing an existing table
var myTable = db.GetTable("my_table");
// Insert a row of data.
myTable.Insert("id", "name").Values(1, "Imani").Values(2, "Adam").Execute();

Python Code

# Accessing an existing table
my_table = db.get_table('my_table')
# Insert a row of data.
my_table.insert(['id','name']).values(1, 'Imani').values(2, 'Adam').execute()

Java Code

// Accessing an existing table
Table myTable = db.getTable("my_table");
// Insert a row of data.
myTable.insert("id", "name").values(1, "Imani").values(2, "Adam").execute();

C++ Code

// Accessing an existing table
var myTable = db.getTable("my_table");
// Insert a row of data.
myTable.insert("id", "name").values(1, "Imani").values(2, "Adam").execute();

Рис. 6.1. Синтаксис Table.insert()

Content is described in the surrounding text.

Table.select()

Table.select() и collection.find() используют различные методы для сортировки результатов. Table.select() следует за языковым обозначением SQL и вызывает метод сортировки orderBy(). Collection.find() так не делает. Используйте метод sort(), чтобы сортировать результаты, возвращенные Collection.find(). Близость к стандарту SQL считают более важной, чем однородность API.

Рис. 6.2. Синтаксис Table.select()

Content is described in the surrounding text.

Table.update()

Рис. 6.3. Синтаксис Table.update()

Content is described in the surrounding text.

Table.delete()

Рис. 6.4. Синтаксис Table.delete()

Content is described in the surrounding text.

Поиск

 

Найди своих коллег!

Вы можете направить письмо администратору этой странички, Алексею Паутову. mailto:alexey.v.pautov@mail.ru