วันนี้จะมาแนะนำวิธีการ Debug Query บน MySQL หรือเรียกอีกอย่าง คือ Profiler นั่นเอง ซึ่งการทำ Profiler นั้น มันมีประโยชน์อย่างมากเลยในการวิเคราะห็ Process/Query ที่ทำงานอยู่บน DataBase ในเวลานั้น ทำให้เราสามารถรู้ปัญหาต่างๆ หรือเพื่อหาข้อผิดพลาดของ Program ที่เกิดขึ้นระหว่างการเชื่อมต่อ Application กับ Database
สำหรับ MySQL นั้น ในที่นี้เราสามารถทำบน Console Command Line ได้เลย  โดยก่อนอื่นให้ทำการเปิดใช้งาน profiler ก่อน
โดยจะต้องทำการ login เข้า MySQL สะก่อน
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | [root@localhost ~]# mysql -u root -p Enter password: Welcome to the MySQL monitor.  Commands end with ; or \g. Your MySQL connection id is 780 Server version: 5.6.28 MySQL Community Server (GPL) Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> | 
จากนั้นใช้คำสั่ง SET profiling = 1;

เมือเปิด profilling เรียบร้อยแล้ว  ให้ลองใช้ Command SQL เพือ Query ดูนะครับ
ในที่นี้ผมลองใช้คำสั่ง show databases; (ซึ่งเป็นการ list database ออกมา)
แต่การ Debug จริง การ Query ก็อาจจะเป็น SQL Query ของ Application

หลังจากนี้ เราสามารถ monitor หรือ debug query ได้เลย
ในที่นี้ผมจะลอง show profilers ที่เคยมีการ query ทั้งหมดออกมาดู
โดยใช้คำสั่ง show profiles;   (คำสั่งนี้จะเป็นการ list profiler ทั้งหมดออกมาก)

ถ้าหากต้องการทีจะดู Information จากการ Query  เราสามารถกำหนด Query ID ได้เช่นกัน
โดยใช้คำสั่ง  show profile for query 1; (ใส่ Query ID ที่ต้องการดู)

หลังจากที่ไม่ได้ใช้งาน Debug Query Profiler แล้ว ก็ควรจะปิดมันไว้ด้วย  โดยใช้คำสั่ง SET profiling = 0;
วิธีที่สอง
นอกจากการ set profiling ยังมีอีกวิธีในการ monitor query  นั่นก็คือ การอ่าน log นั่นเอง
| 1 2 3 4 5 6 7 | mysql> SHOW VARIABLES LIKE "general_log%"; +------------------+------------------+ | Variable_name | Value | +------------------+------------------+ | general_log | OFF |     <----- ปรกติมันจะปิดอยู่ | general_log_file | ComputerName.log |   <--- log file +------------------+------------------+ | 
ลองทำการ Enable log โดยใช้คำสั่ง SET GLOBAL general_log = ‘ON’
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | mysql> SET GLOBAL general_log = 'ON' -> ; Query OK, 0 rows affected (0.03 sec) ตรวจสอบอีกรอบ mysql> SHOW VARIABLES LIKE "general_log%"; +------------------+------------------+ | Variable_name | Value | +------------------+------------------+ | general_log | ON |   <-------- แสดงว่ามันพร้อมที่จะ Write log ละ | general_log_file | ComputerName.log | +------------------+------------------+ 2 rows in set (0.00 sec) | 
เราสามารถเข้าไปวิเคราะ Log จาก Folder data (Installed path/data)

ถ้าต้องการปิดใช้งาน query log ก็สามารถใช้คำสั่ง SET GLOBAL general_log = ‘OFF’
ขอบคุณครับ
Admin@rockdevper






Comments are closed