8.1.1 处理警告

与执行单个语句类似,提交或回滚事务也可能会触发警告。为了能够处理这些警告,需要检查 Session.commit();Session.rollback(); 返回的响应结果对象。

以下示例演示了这一点。该示例假设测试模式存在,并且集合 my_collection 不存在。

from mysqlsh import mysqlx

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

# Get the Schema test
myDb = mySession.get_schema('test')

# Create a new collection
myColl = myDb.create_collection('my_collection')

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

    # Commit the transaction if everything went well
    reply = mySession.commit()

    # handle warnings
    if reply.warning_count:
      for warning in result.get_warnings():
        print('Type [%s] (Code %s): %s\n' % (warning.level, warning.code, warning.message))

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

    # handle warnings
    if reply.warning_count:
      for warning in result.get_warnings():
        print('Type [%s] (Code %s): %s\n' % (warning.level, warning.code, warning.message))

    # Printing the error message
    print('Data could not be inserted: %s' % str(err))

默认情况下,所有警告都会从服务器发送到客户端。如果已知某个操作会生成许多警告,并且这些警告对应用程序没有价值,则可以禁止发送警告。这有助于节省带宽。session.setFetchWarnings() 控制是在服务器上丢弃警告还是将其发送到客户端。session.getFetchWarnings() 用于了解当前活动的设置。

from mysqlsh import mysqlx

def process_warnings(result):
  if result.get_warnings_count():
    for warning in result.get_warnings():
      print('Type [%s] (Code %s): %s\n' % (warning.level, warning.code, warning.message))
  else:
    print("No warnings were returned.\n")


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

# Disables warning generation
mySession.set_fetch_warnings(False)
result = mySession.sql('drop schema if exists unexisting').execute()
process_warnings(result)

# Enables warning generation
mySession.set_fetch_warnings(True)
result = mySession.sql('drop schema if exists unexisting').execute()
process_warnings(result)