Bài 5 – Lấy dữ liệu từ bảng cơ sở dữ liệu MySQL trong Python

Câu lệnh SELECT để lấy dữ liệu từ bảng trong ngôn ngữ SQL.

Kết nối Python với cơ sở dữ liệu MySQL

Chọn tất cả các trường của bảng

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM customers")

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

Lưu ý: Phương thức fetchall() dùng để kết nối đến tất cả các bản ghi của bảng khi thực hiện câu lệnh truy vấn cuối cùng.

Chọn một số trường của bảng

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT name, address FROM customers")

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

Chọn bản ghi đầu tiên của câu lệnh truy vấn

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("SELECT * FROM customers")

#Trả về bản ghi đầu tiên của câu lệnh truy vấn
myresult = mycursor.fetchone()

print(myresult)

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *