Table of Contents
Python連接MySQL資料庫時,常見問題包括編碼、資料讀取和寫入。解決方法包括設定正確的字元集和校對規則、使用fetchall()讀取資料,以及執行commit()確保資料寫入。正確設定可避免中文亂碼等問題。
連接資料庫
資料庫類型有很多種,像是MySQL、Oracle。即使是同一種資料庫類型,在Python中也有多種套件可以使用,像是MySQLdb、PyMySQL、SQLAlchemy、MySQL Connector Python,但整體而言,語法都大同小異,畢竟資料庫連線所需的資訊不外乎是IP、資料庫名稱、使用者帳號與密碼等。在Python中使用MySQLdb的基本語法大致如下,記得execute裡面的SQL語法一定要加上冒號,否則會出錯。我也在這個愚蠢的錯誤上跌倒過。
import MySQLdb
db = MySQLdb.connect(
host = '主機IP或網址',
user = '資料庫帳號',
passwd = '資料庫密碼',
db = '資料庫名稱')
cursor = db.cursor()
cursor.execute("SELECT * FROM table_name;")編碼問題
編碼問題是資料庫管理中常見的問題,編碼包含又包含了兩個部份,collation和character set。關於這兩者的差別,可以參考這篇文章,〈What is the difference between collation and character set?〉
使用MySQLdb的Insert匯入資料時,因為中文和英文的編碼不同,可能會出現錯誤訊息如下:
cursor.execute("INSERT INTO table_name (col1, col2, col3) VALUES ('台北', '台南', '高雄');")
> UnicodeEncodeError: 'latin-1' codec can't encode characters in position 50-51: ordinal not in range(256)1) 檢查Collation
USE database_name;
SELECT @@character_set_database, @@collation_database;
ALTER DATABASE database_name CHARACTER SET utf8 COLLATE utf8_general_ci;2) 檢查Charater Set
SHOW FULL COLUMNS FROM table_name;
ALTER TABLE table_name CHARACTER SET utf8, COLLATE utf8_general_ci;3) 直接在MySQL Insert看看
可以直接把SQL Query丟到MySQL的介面執行,而不是透過Python。如果成功,代表資料庫的編碼其實是正確的。
INSERT INTO table_name (col1, col2, col3) VALUES ('台北', '台南', '高雄');4) 在MySQLdb.connect中增加參數
db = MySQLdb.connect(
host = '主機IP或網址',
user = '資料庫帳號',
passwd = '資料庫密碼',
db = '資料庫名稱',
charset = 'utf8')fetch all
執行Query時,以下這行SQL只會回傳這張table的總資料筆數。
cursor.execute("SELECT * FROM table_name;")不要緊張,其實一切都正常運作,只要加上以下這行就可以了。
table = cursor.fetchall()commit
使用MySQLdb在MySQL中新增資料時
cursor.execute("INSERT INTO table_name (col1, col2, col3) VALUES (3, 4, 5);")新增後,在Python中檢查一切正常,但到MySQL中卻發現資料根本沒有被寫進資料庫。再一次地,不要緊張,加上這行就可以了。注意,這裡的db會對應到最上面,使用MySQLdb.connect建立連線時的變數名稱。
db.commit()





References: Candy96 Casino bonus
References: Winsane Casino App
References: Bwin Casino Auszahlung
References: Instant payid pokies australia
References: Lollybet Willkommensbonus aquarium-vl.ru
References: Casino dice
References: New payid pokies
References: Best instant payid pokies australia real money getskill.work
References: Hitnspin casino alternative cse.google.co.zw
References: Hitnspin casino demo images.google.nu
References: Hitnspin casino ohne anmeldung
References: Hitnspin casino kundenbewertungen
References: Hitnspin casino aktionscode
References: Hitnspin casino bewertung clients1.google.mg
References: Hitnspin casino login
References: Lollybet Aktionscode
References: Monro Casino Mobile
References: Hit casino
References: Kingmaker Casino Österreich
References: KingMaker echtgeld einzahlung
References: Legiano Casino Deutschland