TP+ORACLE插入数据BUG修复以及获取自增Id支持getLastInsID方法
这些天在做Api接口时候,发现用TP操作Oracle数据库,发现查询修改删除都能执行,
但一旦执行插入操作老是报错。类似问题比如: http://www.thinkphp.cn/bug/3286.html
花了点时间仔细研究一下,发现是BUG.
下面是我的解决办法:
针对版本:ThinkPHP3.2.3
BUG修复:
修改文件:Db\Driver\Oracle.class.php
找到 execute方法,
找到:$this->initConnect(true); 这句
前面加上 $bind = $this->bind; 这句:public function execute($str,$fetchSql=false) {<br>
$bind = $this->bind; //新增这句<br>
$this->initConnect(true);
找到:foreach ($this->bind as $key => $val) { 这句
前面加上 $this->bind = $this->bind ? $this->bind : $bind; 这句: $this->bind = $this->bind ? $this->bind : $bind; //新增这句<br>
foreach ($this->bind as $key => $val) {
找到 $this->lastInsID = $this->_linkID->lastInsertId(); 这句
将其修改为: //修改:<br>
//$this->lastInsID = $this->_linkID->lastInsertId();<br>
$this->lastInsID = $this->lastInsertId($this->table);
Oracle.class.php文件中新增以下代码:/**<br>
* 取得Oracle最近插入的ID<br>
* @access public<br>
*/<br>
public function lastInsertId($sequence = '') {<br>
try {<br>
$lastInsID = $this->_linkID->lastInsertId();<br>
} catch(\PDOException $e) {<br>
//对于驱动不支持PDO::lastInsertId()的情况<br>
try {<br>
$lastInsID = 0;<br>
$seqPrefix = C("DB_SEQUENCE_PREFIX") ? C("DB_SEQUENCE_PREFIX") : 'seq_';<br>
$sequence = $sequence ? $sequence : $seqPrefix.$this->table;<br>
$q = $this->query("SELECT {$sequence}.CURRVAL as t FROM DUAL");<br>
if($q) {<br>
$lastInsID = $q[0]['t'];<br>
}<br>
} catch(\Exception $e) {<br>
//print "Error!: " . $e->getMessage() . "";<br>
//exit;<br>
}<br>
}<br>
return $lastInsID;<br>
}
调用方法:
1.数据库配置: 'DB_PREFIX'=>'tb_',//表名前缀<br>
'DB_SEQUENCE_PREFIX' => 'seq_',//序列名前缀,每个表对应的序列应为: 序列名前缀+表名<br>
'DB_TRIGGER_PREFIX' => 'tig_',//触发器名前缀
2.先创建user数据表
表字段:id, username, password
3.然后创建[序列+触发器]----创建序列<br>
create sequence seq_user<br>
increment by 1 <br>
start with 1<br>
nomaxvalue<br>
nominvalue<br>
nocache;<br>
----创建触发器<br>
create or replace trigger "tig_user"<br>
before insert on tb_user<br>
for each row when(new.id is null)<br>
begin<br>
select seq_user.nextval into :new.id from dual;<br>
end;
4.最后一步,在UserAction中写插入数据代码如下:$data = array(<br>
'phone'=>$phone,<br>
'password'=>md5($password)<br>
);<br>
$r = M('user')->field(true)->add($data); //执行插入并返回上次插入Id<br>
if($r){<br>
//$r = M('user')->getLastInsID(); //获取上次插入Id<br>
echo '上次插入记录:'.$r;<br>
}else{<br>
$this->error('操作失败');<br>
}
AD:真正免费,域名+虚机+企业邮箱=0元