8.1.1处理警告

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

如下面的例子所示。该示例假设测试模式存在,并且集合my_collection不存在。

MySQL Shell JavaScript代码

Var mysqlx = require('mysqlx');//连接服务器var mySession = mysqlx。getSession({主机:'localhost',端口:33060,用户:'user',密码:'密码'});//获取Schema test var myDb = myssession . getschema ('test');//创建一个新的集合var myColl = myDb.createCollection('my_collection');//启动事务myssession . starttransaction ();试试{myColl。添加({“名称”:“罗希特”,“年龄”:18岁的“高度”:1.76}). execute ();myColl。添加({“名称”:“岬”,“年龄”:24日,“身高”:1.65}). execute ();myColl。添加({“名称”:“莱昂”,“年龄”:39岁的“高度”:1.9}). execute (); // Commit the transaction if everything went well var reply = mySession.commit(); // handle warnings if (reply.warningCount){ var warnings = reply.getWarnings(); for (index in warnings){ var warning = warnings[index]; print ('Type ['+ warning.level + '] (Code ' + warning.code + '): ' + warning.message + '\n'); } } print ('Data inserted successfully.'); } catch(err) { // Rollback the transaction in case of an error reply = mySession.rollback(); // handle warnings if (reply.warningCount){ var warnings = reply.getWarnings(); for (index in warnings){ var warning = warnings[index]; print ('Type ['+ warning.level + '] (Code ' + warning.code + '): ' + warning.message + '\n'); } } // Printing the error message print ('Data could not be inserted: ' + err.message); }

MySQL Shell Python代码

从mysqlsh导入mysqlx #连接服务器mySession = mysqlx。Get_session ({'host': 'localhost', 'port': 33060, 'user': 'user', 'password': '密码'}) #获取模式测试myDb = mySession.get_schema('test') #创建一个新的集合myColl = myDb.create_collection('my_collection') #启动一个事务myssession .start_transaction() try: myColl. get_schema('test')添加({“名称”:“罗希特”,“年龄”:18岁的“高度”:1.76}). execute () myColl。添加({“名称”:“岬”,“年龄”:24日,“身高”:1.65}). execute () myColl。add({'name': 'Leon', 'age': 39, 'height': 1.9}).execute() #提交事务如果一切正常reply = myssession . Commit() #处理警告如果回复。warning_count:用于result.get_warnings(): print('Type [%s] (Code %s): %s\n' %(警告。水平,警告。code, warning.message)) print('数据插入成功')Exception as err: #在错误情况下回滚事务reply = myssession . Rollback() #如果回复则处理警告。warning_count:用于result.get_warnings(): print('Type [%s] (Code %s): %s\n' %(警告。水平,警告。#打印错误信息print('数据无法插入:%s' % str(err))

c#代码

//连接到服务器var session = MySQLX.GetSession("server=localhost;port=33060;user=user;password=密码;“);//获取模式测试var db = session.GetSchema("test");//创建一个新的集合var myColl = db.CreateCollection("my_collection");//启动事务会话starttransaction ();int警告计数= 0;try {var result = myColl。添加(new {name = "Rohit",年龄= 18,身高= 1.76}).Execute();warningCount += result.Warnings.Count;result = myColl。添加(new {name = "Misaki",年龄= 24,身高= 1.65}).Execute(); warningCount += result.Warnings.Count; result = myColl.Add(new { name = "Leon", age = 39, height = 1.9}).Execute(); warningCount += result.Warnings.Count; // Commit the transaction if everything went well session.Commit(); if(warningCount > 0) { // handle warnings } Console.WriteLine("Data inserted successfully."); } catch (Exception err) { // Rollback the transaction in case of an error session.Rollback(); if(warningCount > 0) { // handle warnings } // Printing the error message Console.WriteLine("Data could not be inserted: " + err.Message); }

Python代码

导入mysqlx # mysqlx连接到服务器get_session({'host': 'localhost', 'port': 33060, 'user': 'user', 'password': 'password'}) #获取模式测试my_schema = my_session.get_schema('test') #创建一个新的集合my_coll = my_schema.create_collection('my_collection') #启动一个事务my_session.start_transaction() try: my_coll. try: my_coll. try ()添加({“名称”:“罗希特”,“年龄”:18岁的“高度”:1.76}). execute () my_coll。添加({“名称”:“岬”,“年龄”:24日,“身高”:1.65}). execute () my_coll。add({'name': 'Leon', 'age': 39, 'height': 1.9}).execute() #提交事务如果一切顺利result = my_session.commit() #处理警告如果result.get_warnings_count() > 0:结果中的警告。get_warnings():打印('类型[{0}](代码{1}):{2}'。format(warning['level'], warning['code'], warning['msg'])) print('数据插入成功。')except Exception as err: #在出现错误时回滚事务result = my_session.rollback() #处理警告if result.get_warnings_count() > 0: result.get_warnings(): print('Type [{0}] (code{1}):{2}'。format(warning['level'], warning['code'], warning['msg'])) #打印错误信息print('Data could not be insert: {0}'.format(err))

Java代码

/ /出口。“标准交易处理”

c++代码

/* Connector/ c++尚未提供对事务警告的访问——会话方法commit()和rollback()不返回结果对象。* /

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

MySQL Shell JavaScript代码

Var mysqlx = require('mysqlx');函数process_warnings(result){if (result. getwarningcount ()){var warnings = result. getwarnings ();{var警告=警告[index];print('键入['+警告。level + '](代码' +警告。Code + '): ' +警告。Message + '\n');}} else{print("没有返回警告。\n");}} //连接服务器var mySession = mysqlx。getSession({主机:'localhost',端口:33060,用户:'user',密码:'密码'});//禁用警告生成myssession . setfetchwarnings (false);var result = mySession。Sql('如果存在则删除模式').execute();process_warnings(结果);//启用警告生成myssession . setfetchwarnings (true);var result = mySession。Sql('如果存在则删除模式').execute();process_warnings(结果);

MySQL Shell Python代码

from mysqlsh import mysqlx def process_warnings(result): if result.get_warnings_count():用于result.get_warnings()中的警告:print('Type [%s] (Code %s): %s\n' %(警告。水平,警告。code, warning.message)) else: print("No warnings were returned.\n") #连接到服务器mySession = mysqlx。Get_session ({'host': 'localhost', 'port': 33060, 'user': 'user', 'password': '密码'});#禁用生成myssession .set_fetch_warnings(False) result = myssession .set_fetch_warnings(False)Sql('如果存在则删除模式').execute() process_warnings(result)# Enables warning generation mySession.set_fetch_warnings(True) result = mySession.sql('drop schema if exists unexisting').execute() process_warnings(result)

Java代码

//连接到服务器Session myssession = new SessionFactory().getSession("mysqlx://localhost:33060/test?user=user&password=password");Schema db = myssession . getschema ("test");//创建一个新的集合集合myColl = db.createCollection("my_collection");//启动事务myssession . starttransaction ();尝试{结果res = myColl。添加(“{\“\”:\“罗希特\”,\“年龄\”:18}”,“{\“\”:\“岬\”,\“年龄\”:24}”,“{\“\”:\“莱昂\”,\“年龄\”:39}"). execute ();System.out.println (res.getWarningsCount ());迭代器 warnings = res.getWarnings();while (warnings.hasNext()){警告warn = warnings.next();System.out.println(warn.getCode() + ", " + warn.getLevel() + ", " + warn.getMessage())); } mySession.commit(); System.out.println("Data inserted successfully."); } catch (Exception err) { // Rollback the transaction in case of an error mySession.rollback(); // Printing the error message System.out.println("Data could not be inserted: " + err.getMessage()); }