PHP 資料庫讀寫分離的經典例子

來源:互聯網
上載者:User
  1. /**
  2. * mysql讀寫分離
  3. * edit: bbs.it-home.org
  4. */
  5. class db
  6. {
  7. public function __construct($sql)
  8. {
  9. $chestr = strtolower(trim($sql));
  10. //判斷sql語句有select關鍵字的話,就串連讀的資料庫,否則就串連寫資料庫
  11. if(substr($chestr,0,6)=='select')
  12. {
  13. echo 'I am using select db..
    ';
  14. $link = mysql_connect("127.0.0.1:3306", "root", "") or die("Could not connect: " . mysql_error());
  15. mysql_select_db("test");
  16. $result = mysql_query($sql);
  17. while ($row = mysql_fetch_array($result, MYSQL_NUM))
  18. {
  19. printf("%s %s", $row[0],$row[1]);
  20. }
  21. echo mysql_get_host_info($link).mysql_get_server_info($link).mysql_get_proto_info($link).mysql_get_client_info().'
    ';
  22. }
  23. else
  24. {
  25. echo 'I am using insert db..
    ';
  26. $link = mysql_connect("127.0.0.2:3306","root","") or die("Could not connect: " . mysql_error());
  27. mysql_select_db("test");
  28. $result = mysql_query($sql);
  29. echo @mysql_affected_rows($result);
  30. echo mysql_get_host_info($link).mysql_get_server_info($link).mysql_get_proto_info($link).mysql_get_client_info().'
    ';
  31. }
  32. }
  33. }
  34. $d = new db(" update `users` set `select`='fasdf' where `id` =1");
  35. $d2 = new db(" SELECT * from `users`");
複製代碼

附,資料庫讀寫分享的相關解釋。

資料庫的讀寫分離,可以有效降低降低資料庫的壓力。

一個主要資料庫,多個從資料庫的架構,實現讀寫分離,是經常用到的方案。主要資料庫提供寫操作,從資料庫提供讀操作。其實分散資料庫的壓力,並不一定要讀寫分離,但是讀寫分離還是有自身的諸多好處的。比如:1、有利於資料庫的負載平衡實現。2、有利於實現主從資料庫熱備份。如果不分離,那麼就要考慮做雙向熱備份策略了。這個的配置比較複雜,並且出問題後也比較麻煩。3、有利於保持資料庫的高可用性,特別是在資料庫叢集的環境。4、最後,實現讀寫分離後,對mysql的查詢速度以及穩定性會更有信心。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.