8000 MySQL 2 prepare for YouTube · potchangelo/python-mysql-excel@506b3ac · GitHub
[go: up one dir, main page]

Skip to content

Commit 506b3ac

Browse files
committed
MySQL 2 prepare for YouTube
1 parent 2423d30 commit 506b3ac

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

scripts/export_data_06.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Export ข้อมูลจาก Database MySQL ออกมาเป็นไฟล์ Excel (.xlsx)
2+
# เป็นการ Export ข้อมูลสินค้าทุกแถว
3+
# และรวมแฮชแท็กทั้งหมดของสินค้าแต่ละอัน มาแสดงด้วย
4+
5+
import mysql.connector
6+
from openpyxl import Workbook
7+
8+
def run():
9+
# Database
10+
# - เชื่อมต่อ Database (เปลี่ยนค่า Connection เป็นของเครื่องตัวเองเน่อ)
11+
db = mysql.connector.connect(
12+
host="localhost",
13+
port=3306,
14+
user="root",
15+
password="password1234",
16+
database='golf_want_to_buy'
17+
)
18+
19+
# - ส่งคำสั่ง SQL ไปให้ MySQL ทำการโหลดข้อมูล
20+
# - Python จะรับข้อมูลทั้งหมดมาเป็น List ผ่านคำสั่ง fetchall()
21+
cursor = db.cursor()
22+
sql = '''
23+
SELECT p.id AS id, p.title AS title, p.price AS price, GROUP_CONCAT(ph.hashtag SEPARATOR ' ') AS hashtags
24+
FROM products AS p
25+
LEFT JOIN (
26+
SELECT ph1.product_id AS product_id, h1.hashtag AS hashtag
27+
FROM products_hashtags AS ph1
28+
LEFT JOIN hashtags AS h1
29+
ON ph1.hashtag_id = h1.id
30+
) AS ph
31+
ON p.id = ph.product_id
32+
GROUP BY p.id;
33+
'''
34+
cursor.execute(sql)
35+
products = cursor.fetchall()
36+
37+
# Excel
38+
# - สร้างไฟล์ใหม่ สร้างชีท และใส่แถวสำหรับเป็นหัวข้อตาราง
39+
workbook = Workbook()
40+
sheet = workbook.active
41+
sheet.append(['ID', 'ชื่อสินค้า', 'ราคา', 'แฮชแท็ก'])
42+
43+
# - ใส่ข้อมูลทีละอัน เพิ่มลงไปทีละแถว
44+
for p in products:
45+
print(p)
46+
sheet.append(p)
47+
48+
# - Export ไฟล์ Excel
49+
workbook.save(filename="./files/exported_06.xlsx")
50+
51+
# ปิดการเชื่อมต่อ Database
52+
cursor.close()
53+
db.close()

0 commit comments

Comments
 (0)
0