Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 3be70b4

Browse filesBrowse files
committed
One more import example
1 parent ceb7a04 commit 3be70b4
Copy full SHA for 3be70b4

File tree

2 files changed

+65
-0
lines changed
Filter options

2 files changed

+65
-0
lines changed

‎files/imported_05.xlsx

Copy file name to clipboard
5.77 KB
Binary file not shown.

‎scripts/import_data_05.py

Copy file name to clipboard
+65Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# Import ข้อมูลจากไฟล์ Excel (.xlsx) เข้าสู่ Database MySQL
2+
# เป็นการ Import ข้อมูลทุกแถวมาใส่ใน products
3+
# แต่จะเอาข้อมูลประเภทสินค้า แยกไปใส่ใน categories (ถ้ายังไม่มี)
4+
# และที่สำคัญ ต้องเชื่อม products และ categories เข้ากันให้เรียบร้อย
5+
6+
import mysql.connector
7+
from openpyxl import load_workbook
8+
9+
def run():
10+
# Excel
11+
# - โหลดไฟล์ และโหลดชีทที่เปิดอยู่
12+
workbook = load_workbook('./files/imported_05.xlsx')
13+
sheet = workbook.active
14+
15+
# Database
16+
# - เชื่อมต่อ Database (เปลี่ยนค่า Connection เป็นของเครื่องตัวเองเน่อ)
17+
db = mysql.connector.connect(
18+
host="localhost",
19+
port=3306,
20+
user="root",
21+
password="password1234",
22+
database='golf_want_to_buy_completed'
23+
)
24+
cursor = db.cursor()
25+
26+
# - เอาเฉพาะข้อมูลสินค้ามาใส่ใน List
27+
products_values = []
28+
for row in sheet.iter_rows(min_row=2, values_only=True):
29+
product = (row[0], row[1], row[2])
30+
print(product)
31+
products_values.append(product)
32+
33+
# - เพิ่มข้อมูลสินค้า
34+
sql = '''
35+
INSERT INTO products (title, price, is_necessary)
36+
VALUES (%s, %s, %s);
37+
'''
38+
cursor.executemany(sql, products_values)
39+
db.commit()
40+
print('เพิ่มสินค้าจำนวน ' + str(cursor.rowcount) + ' แถว')
41+
42+
# - ดึง ID ของสินค้าแรกที่เพิ่มไปเมื่อกี๊ มาเตรียมตัวใช้
43+
first_id = cursor.lastrowid
44+
45+
# - เอาเฉพาะข้อมูลโน้ตสินค้ามาใส่ใน List และผูก id สินค้าด้วย
46+
product_notes_values = []
47+
for (p_id, row) in enumerate(sheet.iter_rows(min_row=2, values_only=True), first_id):
48+
notes = row[3]
49+
if notes is not None:
50+
product_note = (notes, p_id)
51+
print(product_note)
52+
product_notes_values.append(product_note)
53+
54+
# - เพิ่มข้อมูลโน้ตสินค้า
55+
sql = '''
56+
INSERT INTO product_notes (notes, product_id)
57+
VALUES (%s, %s);
58+
'''
59+
cursor.executemany(sql, product_notes_values)
60+
db.commit()
61+
print('เพิ่มโน้ตสินค้าจำนวน ' + str(cursor.rowcount) + ' แถว')
62+
63+
# ปิดการเชื่อมต่อ Database
64+
cursor.close()
65+
db.close()

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.