Python MySQL Chọn từ
Chọn từ một bảng
Để chọn từ một bảng trong MySQL, hãy sử dụng câu lệnh "SELECT":
Ví dụ
Chọn tất cả bản ghi từ bảng "khách hàng" và hiển thị kết quả:
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)
Chạy ví dụ » Lưu ý: Chúng tôi sử dụng phương thức fetchall()
để tìm nạp tất cả các hàng từ câu lệnh được thực thi cuối cùng.
Chọn cột
Để chỉ chọn một số cột trong bảng, hãy sử dụng câu lệnh "SELECT" theo sau là (các) tên cột:
Ví dụ
Chỉ chọn cột tên và địa chỉ:
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ạy ví dụ » Sử dụng phương thức getone()
Nếu bạn chỉ quan tâm đến một hàng, bạn có thể sử dụng phương thức fetchone()
.
Phương thức fetchone()
sẽ trả về hàng đầu tiên của kết quả:
Ví dụ
Chỉ tìm nạp một hà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.fetchone()
print(myresult)
Chạy ví dụ »