# 用Python連接資料庫 #### 一開始需要先對連接的參數做設定 在開始前,會先需要下載python的lib ``` import pymysql # 資料庫參數設定 db_settings = { "host": "127.0.0.1", "port": 3306, #自己的mysql使用的port "user": "root", #自己的使用者名稱 "password": "自己所使用的密碼", "db": "資料庫名稱", "charset": "utf8" #代表語言是中文 } ``` port和使用者名稱可以在自己mysql的面板中觀察到 (藍色的部分是使用者名稱, 黃色的是port代號) ↓  進入mysql連接後,可以看到自己的資料庫叫什麼名字↓  #### 第二步就是對資料庫開始做連接 建立連接後,需要再建立一個cursor物件,因為需要cursor物件去對資料庫執行指令。 ``` import pymysql # 資料庫參數設定 db_settings = { "host": "127.0.0.1", "port": 3306, "user": "root", "password": "0708", "db": "store", "charset": "utf8" } #有可能會出錯,因此用try except語法,只要一出錯,馬上就把錯誤訊息發出,方便修改 def getDiscount() : try : #建立connection物件 connection = pymysql.connect(**db_settings) #建立cursor物件 with connection.cursor() as cursor: command = "指令" cursor.execute(command) result = cursor.fetchall() return(result) except Exception as ex: return(ex) print(getDiscount) ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up