Spec-Zone.ru › MySQL Connectors 1.0

8.1.2 Обработка ошибок

При написании скриптов для MySQL Shell часто можно просто полагаться на обработку исключений, выполняемую MySQL Shell. Для всех остальных языков требуется либо правильная обработка исключений для перехвата ошибок, либо традиционный шаблон обработки ошибок, если язык не поддерживает исключения.

Обработку ошибок по умолчанию можно изменить, создав пользовательскую SessionContext и передав ее функции mysqlx.getSession(). Это позволяет переключиться с обработки исключений на проверку ошибок на основе результатов.

Следующий пример демонстрирует, как выполнить правильную обработку ошибок. Пример предполагает, что схема test существует и что коллекция my_collection существует.

Код JavaScript MySQL Shell

var mysqlx = require('mysqlx');

var mySession;

try {
  // Connect to server on localhost
  mySession = mysqlx.getSession( {
    host: 'localhost', port: 33060,
    user: 'user', password: 'password' } );
}
catch (err) {
  print('The database session could not be opened: ' + err.message);
}

try {
  var myDb = mySession.getSchema('test');

  // Use the collection 'my_collection'
  var myColl = myDb.getCollection('my_collection');

  // Find a document
  var myDoc = myColl.find('name like :param').limit(1)
    .bind('param','L%').execute();

  // Print document
  print(myDoc.first());
}
catch (err) {
  print('The following error occurred: ' + err.message);
}
finally {
  // Close the session in any case
  mySession.close();
}
    

Код Python MySQL Shell

from mysqlsh import mysqlx

mySession

try:
        # Connect to server on localhost
        mySession = mysqlx.get_session( {
                'host': 'localhost', 'port': 33060,
                'user': 'user', 'password': 'password' } )

except Exception as err:
        print('The database session could not be opened: %s' % str(err))

try:
        myDb = mySession.get_schema('test')

        # Use the collection 'my_collection'
        myColl = myDb.get_collection('my_collection')

        # Find a document
        myDoc = myColl.find('name like :param').limit(1).bind('param','L%').execute()

        # Print document
        print(myDoc.first())
except Exception as err:
        print('The following error occurred: %s' % str(err))
finally:
        # Close the session in any case
        mySession.close()
    

Код JavaScript Node.js

var mysqlx = require('@mysql/xdevapi');

// Connect to server on localhost
mysqlx
  .getSession({
    host: 'localhost',
    port: 33060,
    user: 'user',
    password: 'password'
  })
  .then(function (mySession) {
    // This can't throw an error as we check existence at a later operation only
    var myDb = mySession.getSchema('test');

    // Use the collection 'my_collection'
    // This can't throw an error as we check existence at a later operation only
    var myColl = myDb.getCollection('my_collection');

    // Find a document
    return myColl
      .find('name like :param')
      .limit(1)
      .bind('param','L%')
      .execute(function (row) {
        console.log(row);
      })
      .then(function () {
        return session.close();
      })
      .catch(function (err) {
        console.log('The following error occurred: ' + err.message);
      });
  })
  .catch (err) {
    console.log('The database session could not be opened: ' + err.message);
  });

Код C#

Session mySession = null;
try
{
  // Connect to server on localhost
  mySession = MySQLX.GetSession("mysqlx://user:password@localhost:33060");

  try
  {
    Schema myDb = mySession.GetSchema("test");

    // Use the collection 'my_collection'
    Collection myColl = myDb.GetCollection("my_collection");

    // Find a document
    DocResult myDoc = myColl.Find("name like :param").Limit(1).Bind("param", "L%").Execute();

    // Print document
    Console.WriteLine(myDoc.FetchOne());
  }
  catch (Exception err)
  {
    Console.WriteLine("The following error occurred: " + err.Message);
  }
  finally
  {
    // Close the session in any case
    mySession.Close();
  }
}
catch (Exception err)
{
  Console.WriteLine("The database session could not be opened: " + err.Message);
}

Код Python

import mysqlx

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

# Get the Schema test
my_schema = my_session.get_schema('test')

# Create a new collection
my_coll = my_schema.create_collection('my_collection')

# Start a transaction
my_session.start_transaction()
try:
    my_coll.add({'name': 'Rohit', 'age': 18, 'height': 1.76}).execute()
    my_coll.add({'name': 'Misaki', 'age': 24, 'height': 1.65}).execute()
    my_coll.add({'name': 'Leon', 'age': 39, 'height': 1.9}).execute()

    # Commit the transaction if everything went well
    result = my_session.commit()

    # handle warnings
    if result.get_warnings_count() > 0:
        for warning in result.get_warnings():
            print('Type [{0}] (Code {1}): {2}'.format(warning['level'], warning['code'], warning['msg']))

    print('Data inserted successfully.')
except Exception as err:
    # Rollback the transaction in case of an error
    my_session.rollback()

    # handle warnings
    if reply.get_warnings_count() > 0:
        for warning in result.get_warnings():
            print('Type [{0}] (Code {1}): {2}'.format(warning['level'], warning['code'], warning['msg']))

    # Printing the error message
    print('Data could not be inserted: {0}'.format(err))
    

Код Java

import com.mysql.cj.xdevapi.*;

Session mySession;

try {
    // Connect to server on localhost
    mySession = new SessionFactory().getSession("mysqlx://localhost:33060/test?user=user&password=password");

    try {
        Schema myDb = mySession.getSchema("test");

        // Use the collection 'my_collection'
        Collection myColl = myDb.getCollection("my_collection");

        // Find a document
        DocResult myDoc = myColl.find("name like :param").limit(1).bind("param", "L%").execute();

        // Print document
        System.out.println(myDoc.fetchOne());
    } catch (XDevAPIError err) { // special exception class for server errors
        System.err.println("The following error occurred: " + err.getMessage());
    } finally {
        // Close the session in any case
        mySession.close();
    }
} catch (Exception err) {
    System.err.println("The database session could not be opened: " + err.getMessage());
} 

Код C++

#include <mysqlx/xdevapi.h>

try
{
  // Connect to server on localhost
  Session session(33060, "user", "password");

  try
  {
    Schema db = session.getSchema("test");

    // Use the collection 'my_collection'
    Collection myColl = db.getCollection("my_collection");

    // Find a document
    auto myDoc = myColl.find("name like :param").limit(1)
                       .bind("param", "L%").execute();

    // Print document
    cout << myDoc.fetchOne() << endl;

    // Exit with success code
    exit(0);
  }
  catch (const Error &err)
  {
    cout << "The following error occurred: " << err << endl;
    exit(1);
  }

  // Note: session is closed automatically when session object
  // is destructed.
}
catch (const Error &err)
{
  cout << "The database session could not be opened: " << err << endl;

  // Exit with error code
  exit(1);
}

© 2025 Oracle
Licensed under the GPLv2 License.
https://docs.oracle.com/cd/E17952_01/x-devapi-userguide-en/error-handling.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API