Initial commit
This commit is contained in:
60
create_and_insert_pizzas.py
Normal file
60
create_and_insert_pizzas.py
Normal file
@@ -0,0 +1,60 @@
|
||||
import mysql.connector
|
||||
from mysql.connector import Error
|
||||
import random
|
||||
|
||||
# 資料庫連線資訊
|
||||
db_config = {
|
||||
'host': 'mysql.theaken.com',
|
||||
'port': 33306,
|
||||
'database': 'db_A021',
|
||||
'user': 'A021',
|
||||
'password': 'wJk1O5qtP7pf'
|
||||
}
|
||||
|
||||
# 披薩名稱列表
|
||||
pizza_names = [
|
||||
'瑪格麗特', '夏威夷', '海鮮總匯', '燻雞蘑菇', '蔬菜總匯',
|
||||
'德式香腸', '四種起司', '韓式泡菜', '泰式酸辣', 'BBQ烤肉'
|
||||
]
|
||||
|
||||
# 披薩尺寸列表
|
||||
pizza_sizes = ['S', 'M', 'L', 'XL']
|
||||
|
||||
def create_and_insert_pizzas():
|
||||
try:
|
||||
# 建立資料庫連線
|
||||
connection = mysql.connector.connect(**db_config)
|
||||
cursor = connection.cursor()
|
||||
|
||||
# 創建pizzas表
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS pizzas (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(50) NOT NULL,
|
||||
size VARCHAR(10) NOT NULL,
|
||||
price INT NOT NULL
|
||||
)
|
||||
""")
|
||||
|
||||
# 新增10筆披薩資料
|
||||
for i in range(10):
|
||||
name = random.choice(pizza_names)
|
||||
size = random.choice(pizza_sizes)
|
||||
price = random.randint(100, 500)
|
||||
|
||||
query = "INSERT INTO pizzas (name, size, price) VALUES (%s, %s, %s)"
|
||||
cursor.execute(query, (name, size, price))
|
||||
|
||||
# 提交交易
|
||||
connection.commit()
|
||||
print("pizzas 的模擬資料!")
|
||||
|
||||
except Error as e:
|
||||
print(f"資料庫錯誤: {e}")
|
||||
finally:
|
||||
if connection.is_connected():
|
||||
cursor.close()
|
||||
connection.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
create_and_insert_pizzas()
|
Reference in New Issue
Block a user