MySQL Shell  8.0.16
Unified development interface for MySQL Products
Parameter Binding

Parameter Binding

It is good practice to not use values directly on expression strings. The way this is using a parameter or place holder on the expression to replace the real value, later the value is associated to the defined parameter or place holder.

There are two ways to achieve this:

Anonymous Binding

Available on SQL strings, allows removing values from expression through the use of place holders. To finally associate the corresponding value just call the .bind(<value>) function.

nodeSession = mysqlx.getNodeSession('mike:s3cr3t!@localhost:33060')
# Loads the adult customers whose name starts with S
result = nodeSession.sql('select * from test.customers where name like ? and age < ?').bind('S%').bind(18).execute()
The bind function must be called for each place holder on the expression, otherwise an error will occur.

Named Binding

Available on the CRUD operations, allows removing values from expressions through the use of named parameters. To finally associate the corresponding parameter values, call the .bind(<parameter>, <value>) function.

// Collection.find() function with fixed values
var myColl = db.getCollection('my_collection');
var myRes1 = myColl.find('age = 15').execute();
// Using the .bind() function to bind parameters
var myRes2 = myColl.find('name = :param1 AND age = :param2').bind('param1','jack').bind('param2', 17).execute();
// Using named parameters
myColl.modify('name = :param').set('age', 37).
bind('param', 'clare').execute();
// Binding works for all CRUD statements except add()
var myRes3 = myColl.find('name like :param').
bind('param', 'J%').execute();

Each CRUD operation creates a binding context, in order to succeed all the defined parameters must have a value. A parameter could be used several times on the operation, even so, only one value can be assigned to it. If bind is called several times for the same parameter the last value will override the previous ones.

// one bind() per parameter
var myColl = db.getCollection('relatives');
var juniors = myColl.find('alias = "jr"').execute().fetchAll();
for (var index in juniors){
myColl.modify('name = :param').
bind('param', juniors[index].name).execute();