Codeigniter $this->db->reconnect(); usage

2019-06-25 04:37发布

问题:

I’m not autoloading db because most pages of my application don’t need db processing otherwise whole thing will slow down. What I want to do is not to establish a new connection to db when there is one already alive and use it instead not to bother server-db. So how do I implement $this->db->reconnect(); to my example below? I read user guide but no exact example there.

Note : If I necessary to use $this->db->close(); and $this->db->initialize(); then please help me implement them as well because I heard that calling $this->db->reconnect(); with autoloading disabled will throw an error.

I’m using CI 2.1

Thanks

class Test_model extends CI_Model
{
 public function __construct()
 {
  parent::__construct();

  $this->load->database();
 }

 public function function_a($id)
 {
  $this->db->protect_identifiers('year');

  $sql = "SELECT * FROM year WHERE id = ?";

  $data['dbquery'] = $this->db->query($sql, array($id));

  return $data['dbquery'];
 }

 public function function_b($id)
 {
  $this->db->protect_identifiers('month');

  $sql = "SELECT * FROM month WHERE id = ?";

  $data['dbquery'] = $this->db->query($sql, array($id));

  return $data['dbquery'];
 }


 public function function_c($id)...
 public function function_d($id)...
 public function function_e($id)...
} 

回答1:

Basically if you keep pconnect=false in database.php then the connection will be closed at the end of each script’s execution automatically and by default it set to false.

Well if you want then you can use

$this->db->close();

after every query execution to close the connection manually and use

$this->db->initialize();

before any query execution to initialize the connection again after closing it.



回答2:

The best way to do it is just close the connection and reconnect manually with:

$this->db->close();
$this->db->initialize();