簡體   English   中英

檢查php腳本中是否已存在特定的mysql連接?

[英]Check if a specific mysql connection already exists during a php script?

我有一個每個數據庫表對象的類。 每個類負責連接/查詢/數據格式(數據庫表特定邏輯),因為我更喜歡為每個類分配連接以獲得更好的模塊性。 此外,我正在為某些表和查詢使用特定連接。

我的問題是如何檢查連接是否已經存在,以便它不會啟動另一個連接?

基本上我想檢查是否已經建立了具有相同用戶名/密碼/數據庫的連接。 或者這不是必需的,因為mySql不會為同一個用戶啟動新連接? 如果是這樣,請解釋。

經過進一步的研究發現這是不可能的......它需要獲取線程id並使用帶有線程id的conn,它將像一個持久的conn; 或者它需要跟蹤腳本中使用的每個線程ID,這有點無用。

還沒有一個spimple方法這樣做...持久連接可以是一個選擇但是你必須照顧連接清理和再次sux :)

PS:最終我確實在我的應用程序運行期間為連接創建了一個跟蹤系統(那些說它們存儲在全局可用對象中的人我們是對的)。 在單例類對象中的2個數組中存儲conn對象和conn params,檢查params是否已經存在於params數組中,如果不是則創建新的conn,如果是,則從數組鍵獲取conn對象與params相同被發現......我已經為此做了一個架構但是不想使用那個類...不是我開始的邏輯:),而且還想把它放在一個庫項目中,這就是為什么我在尋找一個簡單而抽象的解決方案,但只有一個特定的解決方案:)

我建議你讀這個 - 我想這會對你有幫助http://www.php.net/manual/en/features.persistent-connections.php

如果每個類必須具有不同的連接,則可以使用靜態類屬性來保存連接,並使用單例模式來檢索它。

class SomeTable {
  // Connection resource as a static property 
  // Since it is static, it will be shared by all instances of class SomeTable
  public static $db = FALSE;

  // Static method to retrieve the connection
  // or create it if it doesn't exist
  public static function get_conn() {
    if (self::$db) {
      // Just return the connection if it already exists
      return self::$db;
    }
    else {
      // If it doesn't already exist, create it and return it
      self::$db = mysql_connect(...);
      return self::$db;
    }
  }

  // In other methods, use self::get_conn()
  public function someQuery() {
     $sql = "SELECT col FROM tbl";
     // Call the connection singleton explicitly
     // as the second param to mysql_query()
     $result = mysql_query($sql, self::get_conn());
  }
}
  • 為每個類創建新連接不是一個好主意。 它可能是模塊化的,但你的mysql服務器很快就會膨脹, too may connections錯誤。

我建議使用單例模式和一些OO。

class Singleton{
    private static $instance=null;
    public function connection(){
        if(self::$instance==null){
            self::$instance = mysql_connect(); // define it in your way,
        }
        return self::$connection;
    }
}

class TableA extends Singleton{
    function find($id){
        $query="select * from `A` where `id`='$id'";
        mysql_query($query, $this->connection());
        ... // other codes
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM