8.1.2 錯誤處理

當為 MySQL Shell 編寫指令碼時,您通常可以簡單地依賴 MySQL Shell 完成的例外處理。對於所有其他語言,若要擷取錯誤,則需要適當的例外處理,如果語言不支援例外,則需要使用傳統的錯誤處理模式。

預設錯誤處理可以透過建立自訂的 SessionContext 並將其傳遞至 mysqlx.getSession() 函數來變更。這可以切換從例外到以結果為基礎的錯誤檢查。

以下範例示範如何執行適當的錯誤處理。此範例假設測試綱要存在,且集合 my_collection 存在。

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()