將UTF-8 編碼資料匯入MySQL 表
將包含非英文字元的大型CSV 檔案匯入SQL 表時,必須正確處理UTF-8 編碼以防止字元損壞。
載入UTF-8 編碼資料使用Python 的LOAD DATA LOCAL INFILE 指令匯入MySQL 表,請依照下列步驟操作:
<code class="python">import mysql.connector conn = mysql.connector.connect( user='username', password='password', host='localhost', database='database' ) cursor = conn.cursor() # Create a table with a UTF-8 character set query = """ CREATE TABLE IF NOT EXISTS utf8_table ( id INT AUTO_INCREMENT PRIMARY KEY, data VARCHAR(255) CHARACTER SET utf8 ); """ cursor.execute(query) conn.commit() # Load the UTF-8 encoded CSV file query = """ LOAD DATA INFILE 'utf8_data.csv' IGNORE INTO TABLE utf8_table CHARACTER SET UTF8 FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' """ cursor.execute(query) conn.commit() cursor.close() conn.close()</code>
以上是如何使用Python的LOAD DATA INFILE指令將UTF-8編碼的資料匯入MySQL表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!