TP+ORACLE插入數據BUG修復以及獲取自增Id支持getLastInsID方法
這些天在作Api接口時候,發現用TP操做Oracle數據庫,發現查詢修改刪除都能執行,
但一旦執行插入操做總是報錯。相似問題好比: http://www.thinkphp.cn/bug/3286.html
花了點時間仔細研究一下,發現是BUG.
下面是個人解決辦法:
針對版本:ThinkPHP3.2.3
BUG修復:
修改文件:Db\Driver\Oracle.class.PHPphp
找到 execute方法,
找到:this−>initConnect(true);這句前面加上bind = $this->bind; 這句:html
public function execute($str,$fetchSql=false) { $bind = $this->bind; //新增這句 $this->initConnect(true);
找到:foreach ($this->bind as $key => $val) { 這句
前面加上 $this->bind = $this->bind ? $this->bind : $bind; 這句:mysql
$this->bind = $this->bind ? $this->bind : $bind; //新增這句 foreach ($this->bind as $key => $val) {
找到 $this->lastInsID = $this->_linkID->lastInsertId(); 這句
將其修改成:sql
//修改: //$this->lastInsID = $this->_linkID->lastInsertId(); $this->lastInsID = $this->lastInsertId($this->table);
Oracle.class.php文件中新增如下代碼:thinkphp
/** * 取得Oracle最近插入的ID * @access public */ public function lastInsertId($sequence = '') { try { $lastInsID = $this->_linkID->lastInsertId(); } catch(\PDOException $e) { //對於驅動不支持PDO::lastInsertId()的狀況 try { $lastInsID = 0; $seqPrefix = C("DB_SEQUENCE_PREFIX") ? C("DB_SEQUENCE_PREFIX") : 'seq_'; $sequence = $sequence ? $sequence : $seqPrefix.$this->table; $q = $this->query("SELECT {$sequence}.CURRVAL as t FROM DUAL"); if($q) { $lastInsID = $q[0]['t']; } } catch(\Exception $e) { //print "Error!: " . $e->getMessage() . "</br>"; //exit; } } return $lastInsID; }
調用方法:
1.數據庫配置:數據庫
'DB_PREFIX'=>'tb_',//表名前綴 'DB_SEQUENCE_PREFIX' => 'seq_',//序列名前綴,每一個表對應的序列應爲: 序列名前綴+表名 'DB_TRIGGER_PREFIX' => 'tig_',//觸發器名前綴
2.先建立user數據表
表字段:id, username, passwordfetch
3.而後建立[序列+觸發器]this
----建立序列 create sequence seq_user increment by 1 start with 1 nomaxvalue nominvalue nocache; ----建立觸發器 create or replace trigger "tig_user" before insert on tb_user for each row when(new.id is null) begin select seq_user.nextval into :new.id from dual; end;
4.最後一步,在UserAction中寫插入數據代碼以下:atom
$data = array( 'phone'=>$phone, 'password'=>md5($password) ); $r = M('user')->field(true)->add($data); //執行插入並返回上次插入Id if($r){ //$r = M('user')->getLastInsID(); //獲取上次插入Id echo '上次插入記錄:'.$r; }else{ $this->error('操做失敗'); }