Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ติดตั้ง Python MySQLdb Module ด้วย pip

ขั้นตอนติดตั้ง MySQL Driver สำหรับ Python (ปัจจุบันแนะนำ mysqlclient หรือ PyMySQL แทน MySQLdb เดิม)

ข้อกำหนดเบื้องต้น

  • Python 3.7+ (ติดตั้งแล้ว)
  • MySQL Server 8.0+
  • pip (Python Package Manager)

เปิด Command Prompt (Windows)

  1. กด Win+R พิมพ์ cmd Enter
  2. เข้าโฟลเดอร์ Scripts ของ Python (เช่น C:\Python37\Scripts)
ติดตั้ง Python MySQLdb Module ด้วย pip ติดตั้ง Python MySQLdb Module ด้วย pip

ติดตั้ง Package

ตัวเลือก 1: mysqlclient (C Extension, เร็ว, ต้องมี Visual C++ Build Tools)

pip install mysqlclient

ตัวเลือก 2: PyMySQL (Pure Python, ติดตั้งง่าย, Cross-platform)

pip install PyMySQL
ติดตั้ง Python MySQLdb Module ด้วย pip

ทดสอบการเชื่อมต่อ

import pymysql
conn = pymysql.connect(host='localhost', user='root', password='pass', database='business')
cursor = conn.cursor()
cursor.execute('SELECT VERSION()')
print(cursor.fetchone())
หมายเหตุ: MySQLdb (MySQL-python) ไม่รองรับ Python 3 แล้ว ควรใช้ mysqlclient (Fork ที่รองรับ Py3) หรือ PyMySQL แทน