Laravel 学习--数据库使用初识 1
1. 数据库配置#
- (1) 修改建议用 env,动态使用 config
Oracle 数据库连接配 https://blog.csdn.net/q393364227/article/details/78458690 - (2) 自定义配置
对于配置文件内容介绍:
driver' => 数据库类型 ',
'host' => 地址
'port' => 端口
'database' => 数据库名
'username' => 用户名
'password' => 密码
'prefix' => 表前缀2. 原生数据库操作#
- 1 使用默认链接与指定链接
数据库默认连接操作:$ result = DB::select (‘select from table’);
如果连接方式需要使用 connection 这个函数定义的连接,则
$users = DB::connection('config')->select('select from t'); - 2 原生的 curd
- select
按顺序的传递值方式
$result = DB::connection('test')->select('select from table where id = ?',[3]);
按键值传递值方式
DB::select('select from users where id = :id', ['id' => 1]);
注意: 预处理操作函数都具备 2 个参数位置(sql 语句 、占位符值)
占位符:
1、? 按顺序传递值
2、:Name 按名称传递值。传参都是数组形式 - insert
传值方式与 select 一样
DB::connection('test')->select('insert into table ('count' , 'name') value(?,?),['3','8888888888']'); - update 、delete 同上
DB::update('update users set votes = 100 where name = ?', ['John']);
DB::delete('delete from users');
- select
- 3 事务(使用事务必须把表的数据引擎设置为 innodb,在设计表 -> 选项里面设置)
(1)自动
主要是使用 transaction 这个方法
DB::transaction(function (){
// 修改
$num = DB::update("update goods set goods_name = 'Macos' where id = :id",['id'=>1]);
// 删除
$num1 = DB::delete('delete from goods where id = 7');
var_dump($num,$num1);
try{
if ($num > 0 && $num1 > 0) {
return ' 事务操作成功 ';
}else {
throw new \Exception (' 事务操作失败 ');
}
}catch (Exception $e){
return $e->getMessage();
}
});
注意:务会自动提交。回滚触发条件是抛出异常
(2)手动事务
DB::beginTransaction();
// 修改
$num = DB::update("update goods set goods_name = 'Macos' where id = :id",['id'=>1]);
// 删除
$num1 = DB::delete('delete from goods where id = 7');
if ($num > 0 && $num1 > 0) {
echo ' 事务操作成功 ';
// 事务提交
DB::commit();
}else {
// 事务回滚
echo ' 事务操作失败 ';
DB::rollBack();
} - 4 开启 sql 监听
通过 db 中的 listen 方法。需要添加 AppServiceProvider.php(位置 app\Providers)中的 boot 方法
public function boot()
{
//sql 的监听
DB::listen(function ($query){
// 查看 sql 语句
// echo $query->sql;
// 查看错误码
// var_dump($query->bindings);
// 执行时间
echo $query->time;
});
}
Laravel 调试错误插件:https://blog.csdn.net/qq_38365479/article/...
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: