ThinkPHP5-数据库操作和事务支持

来源:互联网 发布:英文软件公司名称 编辑:程序博客网 时间:2024/05/07 02:22
数据库-基本操作:1、安装mysql追踪器2、MySQL预处理语句prepare、execute3、了解MySQL事务4、安装sqlyong工具1、数据库配置2、query execute原生sql语句 增删改查原生:Db::execute('insert into think_data(name) values("ddd")');增删改都可以用execute,查用query原生:DB::query('select *from demo where id<5');3、参数绑定 命名占位符绑定参数的绑定:$result3 = Db::execute('select *from demo where id=?',[1]);$result4 = Db::execute('insert into think_data(data,name) values(?,?)',['fff','tuan']);占位符的方式:$result5 = Db::execute('insert into think_data(data,name) values(:data,:name)',['data' => 'JUGG','name' => 'sheng'] );或者:$result6 = Db::execute('insert into think_data(data,name) values(:data,:name)',[ 'JUGG', 'sheng'] );4、多个数据库切换查询操作首先,配置config里的数据库,连接其他的数据库,然后,在方法里写入:$result2 = Db::connect('db2')->query('select *from demo');这样得到多个结果集(result1.2.3...),可以实现多个数据库切换查询5、查询构造器(即更简便的出查询)$result6 = Db::table('think_data')->insert(['data' => 'wait','name' => 'BM']); //新增$result6 = Db::table('think_data')->where('id','<','10')->update(['name' => 'who']); //更新$result6 = Db::table('think_data')->where('name','=','wait')->delete(); //删除$result6 = Db::name('data')... //配置里已经配置好了表前缀,此时不用写前缀6、DB链式操作$result7 = Db::name('data')->where('status',1)->field('id,name')->order('id','desc')->select(); //field('id,name')表示只取查询出的数据的id和name数据显示7、事务支持Db::transaction(function (){//事务的mysql代码})例: Db::transaction(function (){ Db::table('think_inno')->delete(3); Db::table('think_inno')->insert(['id' => 1,'name' => 'think','data' => 'not']); }); }try catch //如果try区域的代码块出现错误,那么就执行catch里的代码
原创粉丝点击