围绕PDO的简单MySQL包装器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了围绕PDO的简单MySQL包装器相关的知识,希望对你有一定的参考价值。

A simple wrapper class for mysql around PDO. Also an example on how to use this wrapper for SQLite.
  1. <?php
  2.  
  3. // ------------------------------------------------------------------
  4. // - Database class'es -
  5. // ------------------------------------------------------------------
  6.  
  7. /**
  8. * Main database class
  9. * Works as a layer over PDO. Every static call is forwarded to the PDO object, except for those which are defined
  10. *
  11. **/
  12.  
  13. class DB
  14. {
  15. protected static $DB;
  16.  
  17. private function __construct() {}
  18. private function __clone() {}
  19.  
  20. public static function connect($dbname='default', $host='localhost', $user='root', $password='')
  21. {
  22. try {
  23. // connects to the database
  24. self::$DB = new PDO("mysql:dbname=$dbname;host:=$host" , $user , $password);
  25.  
  26. // set the error reporting attribute
  27. self::$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  28. }
  29. catch(PDOException $e) {
  30. echo $e->getMessage();
  31. }
  32. }
  33.  
  34. public static function close_connection()
  35. {
  36. self::$DB = NULL;
  37. }
  38.  
  39. public static function __callStatic($name, $arguments)
  40. {
  41. return forward_static_call_array(array(self::$DB, $name), $arguments);
  42. }
  43. }
  44.  
  45.  
  46. /**
  47. * A test class
  48. * Using SQLite with 'sqlite::memory:' so that its no need for username, password, etc
  49. * Perfect for quick testing purpose
  50. *
  51. **/
  52.  
  53. class DBtest extends DB
  54. {
  55. public static function connect()
  56. {
  57. try {
  58. self::$DB = new PDO("sqlite::memory:"); // connect to database
  59. echo 'database created in memory <br /> <br />'; // only at debug mode - @TODO: remove it
  60. self::$DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the error reporting attribute
  61. }
  62. catch(PDOException $e) {
  63. echo $e->getMessage();
  64. }
  65. }
  66. }
  67.  
  68. // ------------------------------------------------------------------
  69. // - Initilize a standard connection -
  70. // ------------------------------------------------------------------
  71.  
  72.  
  73. include 'config.php';
  74.  
  75. $dbh::connect( $config['db']['default']['dbname'],
  76. $config['db']['default']['host'],
  77. $config['db']['default']['username'],
  78. $config['db']['default']['password']
  79. );
  80.  
  81.  
  82. ?>

以上是关于围绕PDO的简单MySQL包装器的主要内容,如果未能解决你的问题,请参考以下文章

PHP 简单的MySQL包装PDO

php 使用CRUD方法的简单而安全的PHP PDO数据库包装器......

如何围绕 C++ 代码编写 C 包装器以公开类方法

PDO 包装器返回 NULL

使用 SWIG 围绕 C++ 的 Python 包装器。参数类型无法识别

如何将围绕 C++ 函数的 R 包装器转换为 Python/Numpy