Mysql operations, v0.2, and some solutions to deal with large data volumes

Source: Internet
Author: User
Tags pconnect sql error
Mysql operations, v0.2, and some solutions to deal with large data volumes
/* Mysql simple class by joffe q89949401 bib @ MAD code poet; this class is completely static when used directly include and use mysql: Method () the class is globally visible in php5, so you don't have to worry about the variable range. if you have any comments, please use a private email | qq mail. Currently, there is no method related to the stored procedure. of course, the stored procedure is generally made when the database is created. in the config file, you need to configure the following constant information: LIB: Class storage location DEBUG: whether to enable debug (if it is enabled, error information tracing will be output) TB_EX: database table prefix;

Added the select del update insert big_select big_del function.

*/

  1. /* Mysql simple class by joffe q89949401 bib @ MAD code poet;
  2. When using this class in full static mode, directly include the class and use mysql: Method () name. because the class is globally visible in php5, you don't have to worry about the variable range. if you have any comments, please use a private email | qq mail;
  3. Currently, there are no methods related to stored procedures. of course, stored procedures are generally used to create databases.
  4. The following constant information must be configured in the config file:
  5. LIB: class storage location
  6. DEBUG: whether to enable debug (if it is enabled, error tracking will be output)
  7. TB_EX: database table prefix;
  8. */
  9. Defined ('Lib') or die ('missing config !! ');
  10. Final class mysql {
  11. /**
  12. * Total number of queries
  13. *
  14. * @ Var int
  15. */
  16. Public static $ querynum = 0;
  17. /**
  18. * Connection handle
  19. *
  20. * @ Var object
  21. */
  22. Public static $ link;
  23. /*
  24. Table prefix
  25. @ Var string the following method needs to configure TB_EX as the table prefix in the configuration file
  26. */
  27. Static function add_ex ($ tb ){
  28. Return TB_EX. $ tb_ex. $ tb;
  29. }
  30. /* Whether the mysql database uses a strict type (automatic conversion is not enabled for the mysql type). The default value is false, indicating that type conversion is enabled for mysql, currently, as long as the single quotes used for the insert function are not automatically converted to mysql, related functions may be added in the future.
  31. */
  32. Public static $ is_type_tight = false;
  33. /**
  34. * Constructor
  35. *
  36. * @ Param string $ dbhost host name
  37. * @ Param string $ dbuser
  38. * @ Param string $ dbpw password
  39. * @ Param string $ dbname database name
  40. * @ Param int $ whether pconnect is continuously connected
  41. */
  42. Static function connent ($ dbhost, $ dbuser, $ dbpw, $ dbname = "", $ dbcharset, $ pconnect = 0 ){
  43. If ($ pconnect ){
  44. If (! Self: $ link = @ mysql_pconnect ($ dbhost, $ dbuser, $ dbpw )){
  45. Self: halt ("Can not connect to MySQL server ");
  46. }
  47. } Else {
  48. If (! Self: $ link = @ mysql_connect ($ dbhost, $ dbuser, $ dbpw )){
  49. Self: halt ("Can not connect to MySQL server ");
  50. }
  51. }
  52. If (self: version ()> "4.1 "){
  53. If ($ dbcharset ){
  54. Mysql_query ("SET character_set_connection = {$ dbcharset}, character_set_results = $ dbcharset, character_set_client = binary", self: $ link );
  55. }
  56. If (self: version ()> "5.0.1 "){
  57. Mysql_query ("SET SQL _mode ='' ", self: $ link );
  58. }
  59. }
  60. If ($ dbname ){
  61. Mysql_select_db ($ dbname, self: $ link );
  62. }
  63. }
  64. /**
  65. * Select a database
  66. *
  67. * @ Param string $ dbname
  68. * @ Return
  69. */
  70. Static function select_db ($ dbname ){
  71. Return mysql_select_db ($ dbname, self: $ link );
  72. }
  73. /**
  74. * Retrieve a record from the result set
  75. *
  76. * @ Param object $ query
  77. * @ Param int $ result_type
  78. * @ Return array
  79. */
  80. Static function fetch_array ($ query, $ result_type = MYSQL_ASSOC) {// by default, only the associated array is used and no numeric array is used.
  81. Return mysql_fetch_array ($ query, $ result_type );
  82. }
  83. /**
  84. * Querying SQL
  85. *
  86. * @ Param string $ SQL
  87. * @ Param string $ type
  88. * @ Return object
  89. */
  90. Static function query ($ SQL, $ type = ""){
  91. $ Func = $ type = "UNBUFFERED" & @ function_exists ("mysql_unbuffered_query ")?
  92. "Mysql_unbuffered_query": "mysql_query ";
  93. If (! ($ Query = $ func ($ SQL, self: $ link) & $ type! = "SILENT "){
  94. Self: halt ("MySQL Query Error", $ SQL );
  95. }
  96. Self: $ querynum ++;
  97. Return $ query;
  98. }
  99. /**
  100. * Number of affected items
  101. *
  102. * @ Return int
  103. */
  104. Static function affected_rows (){
  105. Return mysql_affected_rows (self: $ link );
  106. }
  107. /**
  108. * Error message returned
  109. *
  110. * @ Return array
  111. */
  112. Static function error (){
  113. Return (self: $ link )? Mysql_error (self ::$ link): mysql_error ());
  114. }
  115. /**
  116. * Return error code
  117. *
  118. * @ Return int
  119. */
  120. Static function errno (){
  121. Return intval (self: $ link )? Mysql_errno (self ::$ link): mysql_errno ());
  122. }
  123. /**
  124. * Return query results
  125. *
  126. * @ Param object $ query
  127. * @ Param string $ row
  128. * @ Return mixed
  129. */
  130. Static function result ($ query, $ row, $ flname = 0 ){
  131. $ Query = @ mysql_result ($ query, $ row, $ flname );
  132. Return $ query;
  133. }
  134. /**
  135. * Number of results
  136. *
  137. * @ Param object $ query
  138. * @ Return int
  139. */
  140. Static function num_rows ($ query ){
  141. $ Query = mysql_num_rows ($ query );
  142. Return $ query;
  143. }
  144. /**
  145. * Total number of fields
  146. *
  147. * @ Param object $ query
  148. * @ Return int
  149. */
  150. Static function num_fields ($ query ){
  151. Return mysql_num_fields ($ query );
  152. }
  153. /**
  154. * Release result set
  155. *
  156. * @ Param object $ query
  157. * @ Return bool
  158. */
  159. Static function free_result ($ query ){
  160. Return @ mysql_free_result ($ query );
  161. }
  162. /**
  163. * The Auto-increment ID is returned.
  164. *
  165. * @ Return int
  166. */
  167. Static function insert_id (){
  168. Return ($ id = mysql_insert_id (self: $ link)> = 0? $ Id: self ::$ result (self ::$ query ("SELECT last_insert_id ()"), 0 );
  169. }
  170. /**
  171. * Retrieve a row from the result set as an enumerated array
  172. *
  173. * @ Param object $ query
  174. * @ Return array
  175. */
  176. Static function fetch_row ($ query ){
  177. $ Query = mysql_fetch_row ($ query );
  178. Return $ query;
  179. }
  180. /**
  181. * Retrieve column information from the result set and return it as an object
  182. *
  183. * @ Param object $ query
  184. * @ Return object
  185. */
  186. Static function fetch_fields ($ query ){
  187. Return mysql_fetch_field ($ query );
  188. }
  189. Static function select_affectedt_rows ($ rs ){
  190. Return mysql_affected_rows ($ rs, self: $ link );
  191. }
  192. /**
  193. * Returns the mysql version.
  194. *
  195. * @ Return string
  196. */
  197. Static function version (){
  198. Return mysql_get_server_info (self: $ link );
  199. }
  200. /**
  201. * Close the connection.
  202. *
  203. * @ Return bool
  204. */
  205. Static function close (){
  206. Return mysql_close (self: $ link );
  207. }
  208. /**
  209. * Output error message
  210. *
  211. * @ Param string $ message
  212. * @ Param string $ SQL
  213. */
  214. Static function halt ($ message = "", $ SQL = ""){
  215. @ Header ("Content-type: text/html; charset = utf-8 ");
  216. If (DEBUG = 1 ){
  217. $ Debug = debug_backtrace ();
  218. Echo $ message. "\ r \ n
    SQL --> ". $ SQL." \ r \ n
    ERROR_MESSAGE --> ". self: error ().
  219. "\ R \ n
    -------------- Debug -------------- \ r \ n
    ";
  220. Self: echoarray ($ debug );
  221. Echo "\ r \ n
    ------------- Debug end ----------------";
  222. } Else {
  223. Echo 'SQL error ';
  224. }
  225. @ Self: rollback ();
  226. Exit;
  227. }
  228. /////////////////////////// The following is an extended SQL method. //////
  229. /* Insert the array into the table of the data table according to the corresponding relationship of the key value.
  230. Table
  231. Note that these extension methods do not add prefixes to tables by themselves.
  232. */
  233. Static function insert ($ table, $ array ){
  234. $ Temp = ""; $ temp2 = '';
  235. Foreach ($ array as $ key => $ value ){
  236. If (self: $ is_type_tight ){
  237. If (is_string ($ value )){
  238. $ Temp. = "$ key,"; $ temp2. = "'$ value ',";
  239. } Elseif (is_int ($ value | is_null ($ value) | is_float ($ value ))){
  240. $ Value + = 0;
  241. $ Temp. = "$ key,"; $ temp2. = "'$ value ',";
  242. }
  243. } Else {
  244. $ Temp. = "$ key,"; $ temp2. = "'$ value ',";
  245. }
  246. }
  247. $ Temp = substr ($ temp, 0, strlen ($ temp)-1 );
  248. $ Temp2 = substr ($ temp2, 0, strlen ($ temp2)-1 );
  249. $ SQL = "INSERT INTO $ table ($ temp) VALUE ($ temp2 )";
  250. Return self: query ($ SQL );
  251. }
  252. Static function del ($ table, $ where ){
  253. $ SQL = "DELETE FROM {$ table} where {$ where }";
  254. Return self: query ($ SQL );
  255. }
  256. Static function update ($ table, $ array, $ where ){
  257. Foreach ($ array as $ key => $ value ){
  258. $ Temp. = "$ key = '$ value ',";
  259. }
  260. $ Temp = substr ($ temp, 0, strlen ($ temp)-1 );
  261. $ SQL = "update {$ table} set ($ temp) where {$ where }";
  262. Return self: query ($ SQL );
  263. }
  264. /* The select parameter for database query is invalid.
  265. Parameter description: all parameters must be string
  266. The first parameter must be the table name;
  267. Starting from the second parameter,
  268. If "where: XXX" is written, it is considered as the where condition;
  269. If "xxx" is written, it is considered as a key value.
  270. If "by: XXX" is written, it is regarded as sorting.
  271. If "limit: xxx, xxx" is written, it is regarded as paging.
  272. # If the parameter is incorrect, false is returned. if the query is successful, the queried array is returned;
  273. */
  274. Static function select (){
  275. $ Numargs = func_num_args (); // Obtain the number of parameters;
  276. $ Where = ""; $ key = ""; $ limit = ""; $ by = "";
  277. If ($ numargs = 0) {return false ;}
  278. // Echo $ numargs;
  279. If ($ numargs> = 2 ){
  280. $ Arg_list = func_get_args ();
  281. $ Table = $ arg_list [0];
  282. Unset ($ arg_list [0]);
  283. // Print_r ($ arg_list );
  284. Foreach ($ arg_list as $ k => $ value ){
  285. If (preg_match ("# ^ (where :) \ w #", $ value )){
  286. $ Temp = explode (":", $ value );
  287. $ Where = "WHERE {$ temp [1]}";
  288. } Elseif (preg_match ("# ^ by: \ w #", $ value )){
  289. $ Temp = explode (":", $ value );
  290. $ By = "order by {$ temp [1]}";
  291. } Elseif (preg_match ("# ^ limit: \ w #", $ value )){
  292. $ Temp = explode (":", $ value );
  293. $ Limit = "limit {$ temp [1]}";
  294. } Else {
  295. $ Key. = "$ value ,";
  296. }
  297. }
  298. If ($ key = ""){
  299. $ Key = "*";
  300. } Else {
  301. $ Key = substr ($ key, 0, strlen ($ key)-1 );
  302. }
  303. $ SQL _base = "SELECT $ key FROM $ table ";
  304. }
  305. If (! Empty ($ where )){
  306. $ SQL _base. = "$ where ";
  307. }
  308. If (! Empty ($ )){
  309. $ SQL _base. = "$ ";
  310. }
  311. If (! Empty ($ limit )){
  312. $ SQL _base. = "$ limit ";
  313. }
  314. // Echo $ SQL _base;
  315. // Echo $;
  316. $ Rs = self: query ($ SQL _base );
  317. $ Re = array ();
  318. If (self: num_rows ($ rs)> = 1 ){
  319. While ($ info = self: fetch_array ($ rs )){
  320. $ Re [] = $ info;
  321. }
  322. }
  323. Self: free_result ($ rs );
  324. Return $ re;
  325. }
  326. /* Roll back the transaction */
  327. Static function rollback (){
  328. Self: query ('rollback ');
  329. }
  330. /* Start transaction */
  331. Static function begin (){
  332. Self: query ('set AUTOCOMMIT = 0'); // disable automatic submission;
  333. Self: query ('begin'); // starts a transaction;
  334. }
  335. /* Submit the transaction */
  336. Static function commit (){
  337. Self: query ('commit ');
  338. }
  339. Static function echoarray ($ array ){
  340. Foreach ($ array as $ k => $ v ){
  341. If (is_array ($ v )){
  342. If (is_array ($ v )){
  343. Echo"
    --------------------------------
    ";
  344. Self: echoarray ($ v );
  345. }
  346. } Else {
  347. If ($ k = 'line ')
  348. Echo"$ K-> ". $ v ."";
  349. Else
  350. Echo "$ k->". $ v ."";
  351. }
  352. }
  353. }
  354. Function get_server_info (){
  355. Return mysql_get_server_info ();
  356. }
  357. // The following is an optimized query for tables dealing with big data.
  358. /*
  359. Big_select is suitable for large-scale queries. The Coverage Index is used to implement a large offset activity window, so that the query is offset on the covered index rather than on all data, reducing the data check of msql, it is more efficient to join other data. however, for small-scale data, such queries increase complexity and increase the optimizer pressure. for example, if you use limit, 20; mysql will first find 10020 pieces of data and then discard 10000, which is very costly. This function can effectively improve efficiency, but if it is limit 20, it will be a little slower than the direct select statement.
  360. @ Table string the table to be queried, such as "table1"
  361. @ Keys string the key value to be queried. Use "," to separate multiple key values such as "key1, key2, key3" end does not include ", "Try to use less" * "and add some keywords ';
  362. @ Index string primary Index key or unique Index key name, only one such as "id ";
  363. @ Pagesize int page size, required. you don't want to get all the data
  364. @ PageNo page number, starting from 0
  365. @ Orderby string sorting, such as "id desc"; can be empty, but it is not recommended to be empty
  366. @ Where string condition, such as "date> 122424533", can be empty
  367. # Returned array
  368. */
  369. Static function big_select ($ table, $ keys, $ index, $ pagesize, $ pageNo, $ orderby = NULL, $ where = NULL ){
  370. $ Start = $ pageNo * $ pagesize;
  371. If ($ where ){
  372. $ SqlIndex = "SELEECT {$ index} from {$ table} where {$ where }";
  373. } Else {
  374. $ SqlIndex = "SELEECT {$ index} from {$ table }";
  375. }
  376. If ($ orderby ){
  377. $ SqlIndex. = "order by {$ orderby} Limit $ start, $ pagesize ";
  378. } Else {
  379. $ SqlIndex. = "order by Limit $ start, $ pagesize ";
  380. }
  381. $ SQL = "SELECT $ keys FROM {$ table} INNER JOIN ({$ sqlIndex}) AS lim USING ({$ index })";
  382. $ Rs = self: query ($ SQL );
  383. $ Re = array ();
  384. If (self: num_rows ($ rs)> = 1 ){
  385. While ($ info = self: fetch_array ($ rs )){
  386. $ Re [] = $ info;
  387. }
  388. }
  389. Self: free_result ($ rs );
  390. Return $ re;
  391. }
  392. /* If a large volume of data (more than ten thousand rows are expected) is deleted for a long time, the tables or rows that should not be locked will be locked for a long time, to interrupt data that should not be interrupted, the following method is to small a large SQL task (divided into one 5000 rows), but the next operation may cause new data to be inserted during the deletion gap, new data may be deleted because the conditions are met. this method may fail due to timeout.
  393. @ Table string name of the table to be deleted
  394. @ Where string condition can be omitted
  395. # Number of lines deleted by int
  396. */
  397. Static function big_del ($ table, $ where ){
  398. Set_time_limit (0 );
  399. $ SQL = "delete from {$ table} where {$ where} Limit 5000 ";
  400. $ Rows = 0;
  401. $ Eff = 0;
  402. Do {
  403. Self: query ($ SQL );
  404. $ Rows = self: affected_rows ();
  405. $ Eff + = $ rows;
  406. } While ($ rows> 0 );
  407. Return $ eff;
  408. }
  409. }
  410. ?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.