How To Catch Exception DB::unprepared()

Viewed 1589

I want to run SQL script file in Laravel 5.5 and I use DB::unprepared($sql) which is good so far. But I found that DB::unprepared($sql) seems didn't return any error Exception. I try with different method but still didn't work.

Here some Exception class that I tried: \Exception, PDOException, \Illuminate\Database\QueryException, but didn't work.

Try tried get bolean return from DP::unprepared($sql) by doing this $return = DB::unprepared($sql); var_dump($return); but always return TRUE

I tried using DB::statement($sql), but it looks like use only for executing statement per statement. I need to run a whole sql file without any modification.

Could anyone help me how to catch any SQL script error? Any laravel function method that could help me catch SQL exception?

2 Answers

@Kenjiro, I'm sure you already solved your problem, one a half year past. But, if I nailed it, please mark my answer as it will help fellows with the same problem in the future. This post was the first when googling and it has no answer...

Well, it seems that, like me, you were submiting a multistatement query to DB::unprepared.

Say:

$sql = '
    drop temporary table if exists tmp_data;

    create temporary table tmp_data
    select1 *
    from data;'

$result = DB::unprepared($sql)

Even with the typo in select1, the code will run and $result will be true.

To make it work as expected we have to submit each single statement:

$sql = 'drop temporary table if exists tmp_data;'

DB::unprepared($sql);

$sql = '
    create temporary table tmp_data
    select1 *
    from data;'

DB::unprepared($sql)

No need to check the result. The second call to unprepared will raise an exception.

That's it.

You can check it with try catch :

    try { 
      //your code
    } catch(\Illuminate\Database\QueryException $ex){ 
      dd($ex->getMessage()); 
      // Note any method of class PDOException can be called on $ex.
    }

Also check For Reference : Check This out

Related