<?PHPclass MySQL { Private $param; Public $db; Public function__construct () {$this->db =NewSwoole_mysql; $this->param =Array( ' Host ' = ' 127.0.0.1 ', ' user ' = ' root ', ' password ' = ' 123 ', ' database ' and ' = ' Test ', ); } Public function exec($sql) { $this->db->connect ($this->param,function($db,$result) Use($sql) { if($result===false) { Echo"Connection Database failed: Error code:".$db->connect_errno.Php_eol.$db-Connect_error; return false; } $db->query ($sql,function($db,$res) { if($res===false) { //the error property gets the wrong message, and the Errno property gets the error code Echo"SQL statement execution error:".$db-error; } Else if($res===true) { //non-query statement Affected_rows property gets the number of rows affected, insert_id property gets the increment ID of the insert Operation Echo"The SQL statement execution succeeded, affecting the number of rows:".$db-affected_rows; } Else { //Query statement $result as result array Var_dump($res); } $db-Close (); }); }); }}$mysql=New MySQL();
Using asynchronous MySQL Benefits:
- Prevent code blocking and improve code efficiency
Applicable occasions:
- Does not involve shared resources, or read-only to shared resources, that is, non-exclusive operations
- There is no strict relationship on timing.
- Does not require atomic manipulation, or can control atomicity in other ways
- Often time-consuming operations, such as IO operations, because the comparison affects customer experience and usage performance
- Does not affect the main thread logic
Swoole asynchronous MySQL Use