Db.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: liu21st <liu21st@gmail.com>
  10. // +----------------------------------------------------------------------
  11. define('CLIENT_MULTI_RESULTS', 131072);
  12. /**
  13. * ThinkPHP 简洁模式数据库中间层实现类
  14. * 只支持mysql
  15. */
  16. class Db {
  17. static private $_instance = null;
  18. // 是否自动释放查询结果
  19. protected $autoFree = false;
  20. // 是否显示调试信息 如果启用会在日志文件记录sql语句
  21. public $debug = false;
  22. // 是否使用永久连接
  23. protected $pconnect = false;
  24. // 当前SQL指令
  25. protected $queryStr = '';
  26. // 最后插入ID
  27. protected $lastInsID = null;
  28. // 返回或者影响记录数
  29. protected $numRows = 0;
  30. // 返回字段数
  31. protected $numCols = 0;
  32. // 事务指令数
  33. protected $transTimes = 0;
  34. // 错误信息
  35. protected $error = '';
  36. // 当前连接ID
  37. protected $linkID = null;
  38. // 当前查询ID
  39. protected $queryID = null;
  40. // 是否已经连接数据库
  41. protected $connected = false;
  42. // 数据库连接参数配置
  43. protected $config = '';
  44. // 数据库表达式
  45. protected $comparison = array('eq'=>'=','neq'=>'!=','gt'=>'>','egt'=>'>=','lt'=>'<','elt'=>'<=','notlike'=>'NOT LIKE','like'=>'LIKE');
  46. // 查询表达式
  47. protected $selectSql = 'SELECT%DISTINCT% %FIELDS% FROM %TABLE%%JOIN%%WHERE%%GROUP%%HAVING%%ORDER%%LIMIT%';
  48. /**
  49. * 架构函数
  50. * @access public
  51. * @param array $config 数据库配置数组
  52. */
  53. public function __construct($config=''){
  54. if ( !extension_loaded('mysql') ) {
  55. throw_exception(L('_NOT_SUPPERT_').':mysql');
  56. }
  57. $this->config = $this->parseConfig($config);
  58. }
  59. /**
  60. * 连接数据库方法
  61. * @access public
  62. * @throws ThinkExecption
  63. */
  64. public function connect() {
  65. if(!$this->connected) {
  66. $config = $this->config;
  67. // 处理不带端口号的socket连接情况
  68. $host = $config['hostname'].($config['hostport']?":{$config['hostport']}":'');
  69. if($this->pconnect) {
  70. $this->linkID = mysql_pconnect( $host, $config['username'], $config['password'],CLIENT_MULTI_RESULTS);
  71. }else{
  72. $this->linkID = mysql_connect( $host, $config['username'], $config['password'],true,CLIENT_MULTI_RESULTS);
  73. }
  74. if ( !$this->linkID || (!empty($config['database']) && !mysql_select_db($config['database'], $this->linkID)) ) {
  75. throw_exception(mysql_error());
  76. }
  77. $dbVersion = mysql_get_server_info($this->linkID);
  78. if ($dbVersion >= "4.1") {
  79. //使用UTF8存取数据库 需要mysql 4.1.0以上支持
  80. mysql_query("SET NAMES '".C('DB_CHARSET')."'", $this->linkID);
  81. }
  82. //设置 sql_model
  83. if($dbVersion >'5.0.1'){
  84. mysql_query("SET sql_mode=''",$this->linkID);
  85. }
  86. // 标记连接成功
  87. $this->connected = true;
  88. // 注销数据库连接配置信息
  89. unset($this->config);
  90. }
  91. }
  92. /**
  93. * 释放查询结果
  94. * @access public
  95. */
  96. public function free() {
  97. mysql_free_result($this->queryID);
  98. $this->queryID = 0;
  99. }
  100. /**
  101. * 执行查询 主要针对 SELECT, SHOW 等指令
  102. * 返回数据集
  103. * @access public
  104. * @param string $str sql指令
  105. * @return mixed
  106. * @throws ThinkExecption
  107. */
  108. public function query($str='') {
  109. $this->connect();
  110. if ( !$this->linkID ) return false;
  111. if ( $str != '' ) $this->queryStr = $str;
  112. //释放前次的查询结果
  113. if ( $this->queryID ) { $this->free(); }
  114. N('db_query',1);
  115. // 记录开始执行时间
  116. G('queryStartTime');
  117. $this->queryID = mysql_query($this->queryStr, $this->linkID);
  118. $this->debug();
  119. if ( !$this->queryID ) {
  120. if ( $this->debug )
  121. throw_exception($this->error());
  122. else
  123. return false;
  124. } else {
  125. $this->numRows = mysql_num_rows($this->queryID);
  126. return $this->getAll();
  127. }
  128. }
  129. /**
  130. * 执行语句 针对 INSERT, UPDATE 以及DELETE
  131. * @access public
  132. * @param string $str sql指令
  133. * @return integer
  134. * @throws ThinkExecption
  135. */
  136. public function execute($str='') {
  137. $this->connect();
  138. if ( !$this->linkID ) return false;
  139. if ( $str != '' ) $this->queryStr = $str;
  140. //释放前次的查询结果
  141. if ( $this->queryID ) { $this->free(); }
  142. N('db_write',1);
  143. // 记录开始执行时间
  144. G('queryStartTime');
  145. $result = mysql_query($this->queryStr, $this->linkID) ;
  146. $this->debug();
  147. if ( false === $result) {
  148. if ( $this->debug )
  149. throw_exception($this->error());
  150. else
  151. return false;
  152. } else {
  153. $this->numRows = mysql_affected_rows($this->linkID);
  154. $this->lastInsID = mysql_insert_id($this->linkID);
  155. return $this->numRows;
  156. }
  157. }
  158. /**
  159. * 启动事务
  160. * @access public
  161. * @return void
  162. * @throws ThinkExecption
  163. */
  164. public function startTrans() {
  165. $this->connect(true);
  166. if ( !$this->linkID ) return false;
  167. //数据rollback 支持
  168. if ($this->transTimes == 0) {
  169. mysql_query('START TRANSACTION', $this->linkID);
  170. }
  171. $this->transTimes++;
  172. return ;
  173. }
  174. /**
  175. * 用于非自动提交状态下面的查询提交
  176. * @access public
  177. * @return boolen
  178. * @throws ThinkExecption
  179. */
  180. public function commit() {
  181. if ($this->transTimes > 0) {
  182. $result = mysql_query('COMMIT', $this->linkID);
  183. $this->transTimes = 0;
  184. if(!$result){
  185. throw_exception($this->error());
  186. return false;
  187. }
  188. }
  189. return true;
  190. }
  191. /**
  192. * 事务回滚
  193. * @access public
  194. * @return boolen
  195. * @throws ThinkExecption
  196. */
  197. public function rollback() {
  198. if ($this->transTimes > 0) {
  199. $result = mysql_query('ROLLBACK', $this->linkID);
  200. $this->transTimes = 0;
  201. if(!$result){
  202. throw_exception($this->error());
  203. return false;
  204. }
  205. }
  206. return true;
  207. }
  208. /**
  209. * 获得所有的查询数据
  210. * @access public
  211. * @return array
  212. * @throws ThinkExecption
  213. */
  214. public function getAll() {
  215. if ( !$this->queryID ) {
  216. throw_exception($this->error());
  217. return false;
  218. }
  219. //返回数据集
  220. $result = array();
  221. if($this->numRows >0) {
  222. while($row = mysql_fetch_assoc($this->queryID)){
  223. $result[] = $row;
  224. }
  225. mysql_data_seek($this->queryID,0);
  226. }
  227. return $result;
  228. }
  229. /**
  230. * 关闭数据库
  231. * @access public
  232. * @throws ThinkExecption
  233. */
  234. public function close() {
  235. if (!empty($this->queryID))
  236. mysql_free_result($this->queryID);
  237. if ($this->linkID && !mysql_close($this->linkID)){
  238. throw_exception($this->error());
  239. }
  240. $this->linkID = 0;
  241. }
  242. /**
  243. * 数据库错误信息
  244. * 并显示当前的SQL语句
  245. * @access public
  246. * @return string
  247. */
  248. public function error() {
  249. $this->error = mysql_error($this->linkID);
  250. if($this->queryStr!=''){
  251. $this->error .= "\n [ SQL语句 ] : ".$this->queryStr;
  252. }
  253. return $this->error;
  254. }
  255. /**
  256. * SQL指令安全过滤
  257. * @access public
  258. * @param string $str SQL字符串
  259. * @return string
  260. */
  261. public function escapeString($str) {
  262. return mysql_escape_string($str);
  263. }
  264. /**
  265. * 析构方法
  266. * @access public
  267. */
  268. public function __destruct() {
  269. // 关闭连接
  270. $this->close();
  271. }
  272. /**
  273. * 取得数据库类实例
  274. * @static
  275. * @access public
  276. * @return mixed 返回数据库驱动类
  277. */
  278. public static function getInstance($db_config='') {
  279. if ( self::$_instance==null ){
  280. self::$_instance = new Db($db_config);
  281. }
  282. return self::$_instance;
  283. }
  284. /**
  285. * 分析数据库配置信息,支持数组和DSN
  286. * @access private
  287. * @param mixed $db_config 数据库配置信息
  288. * @return string
  289. */
  290. private function parseConfig($db_config='') {
  291. if ( !empty($db_config) && is_string($db_config)) {
  292. // 如果DSN字符串则进行解析
  293. $db_config = $this->parseDSN($db_config);
  294. }else if(empty($db_config)){
  295. // 如果配置为空,读取配置文件设置
  296. $db_config = array (
  297. 'dbms' => C('DB_TYPE'),
  298. 'username' => C('DB_USER'),
  299. 'password' => C('DB_PWD'),
  300. 'hostname' => C('DB_HOST'),
  301. 'hostport' => C('DB_PORT'),
  302. 'database' => C('DB_NAME'),
  303. 'dsn' => C('DB_DSN'),
  304. 'params' => C('DB_PARAMS'),
  305. );
  306. }
  307. return $db_config;
  308. }
  309. /**
  310. * DSN解析
  311. * 格式: mysql://username:passwd@localhost:3306/DbName
  312. * @static
  313. * @access public
  314. * @param string $dsnStr
  315. * @return array
  316. */
  317. public function parseDSN($dsnStr) {
  318. if( empty($dsnStr) ){return false;}
  319. $info = parse_url($dsnStr);
  320. if($info['scheme']){
  321. $dsn = array(
  322. 'dbms' => $info['scheme'],
  323. 'username' => isset($info['user']) ? $info['user'] : '',
  324. 'password' => isset($info['pass']) ? $info['pass'] : '',
  325. 'hostname' => isset($info['host']) ? $info['host'] : '',
  326. 'hostport' => isset($info['port']) ? $info['port'] : '',
  327. 'database' => isset($info['path']) ? substr($info['path'],1) : ''
  328. );
  329. }else {
  330. preg_match('/^(.*?)\:\/\/(.*?)\:(.*?)\@(.*?)\:([0-9]{1, 6})\/(.*?)$/',trim($dsnStr),$matches);
  331. $dsn = array (
  332. 'dbms' => $matches[1],
  333. 'username' => $matches[2],
  334. 'password' => $matches[3],
  335. 'hostname' => $matches[4],
  336. 'hostport' => $matches[5],
  337. 'database' => $matches[6]
  338. );
  339. }
  340. return $dsn;
  341. }
  342. /**
  343. * 数据库调试 记录当前SQL
  344. * @access protected
  345. */
  346. protected function debug() {
  347. // 记录操作结束时间
  348. if ( $this->debug ) {
  349. G('queryEndTime');
  350. Log::record($this->queryStr." [ RunTime:".G('queryStartTime','queryEndTime',6)."s ]",Log::SQL);
  351. }
  352. }
  353. /**
  354. * 获取最近一次查询的sql语句
  355. * @access public
  356. * @return string
  357. */
  358. public function getLastSql() {
  359. return $this->queryStr;
  360. }
  361. /**
  362. * 获取最近插入的ID
  363. * @access public
  364. * @return string
  365. */
  366. public function getLastInsID(){
  367. return $this->lastInsID;
  368. }
  369. }