Để kết nối Python với cơ sở dữ liệu, bạn cần có trình điều khiển, đây là thư viện được sử dụng để Tương tác với cơ sở dữ liệu. Đối với cơ sở dữ liệu MySQL, bạn có 3 lựa chọn Trình điều khiển như vậy
- MySQL/trình kết nối cho Python
- MySQLdb
- PyMySQL
DriverDiscriptionMySQL/Connector for PythonĐây là thư viện được cung cấp bởi cộng đồng MySQL. MySQLdbMySQLdb là một thư viện kết nối với MySQL từ Python, nó được viết bằng ngôn ngữ C và là phần mềm mã nguồn mở miễn phí. PyMySQLĐây là thư viện kết nối với MySQL từ Python và nó là thư viện Python thuần túy. Mục tiêu của PyMySQL là thay thế MySQLdb và hoạt động trên CPython, PyPy và IronPython
PyMySQL là một dự án mã nguồn mở và bạn có thể xem mã nguồn của nó tại đây
- https. //github. com/PyMySQL/PyMySQL
2- Cài đặt PyMySQL
Để cài đặt PyMySQL trên Windows [hoặc Ubuntu/Linux], bạn cần mở cửa sổ CMD và chạy câu lệnh sau
pip install PyMySQL
3- Cơ sở dữ liệu mẫu
"Simplehr" là cơ sở dữ liệu mẫu được sử dụng trong nhiều hướng dẫn về o7planning. Trong bài, tôi cũng sử dụng nó. Bạn có thể tạo cơ sở dữ liệu dựa trên hướng dẫn bên dưới
- Cơ sở dữ liệu mẫu
4- Kết nối MySQL từ Python với PyMySQL
Ví dụ đơn giản sau sử dụng Python để kết nối với MySQL và truy vấn bảng Department
kết nốiVí dụ. py
import pymysql.cursors
# Connect to the database.
connection = pymysql.connect[host='192.168.5.134',
user='root',
password='1234',
db='simplehr',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor]
print ["connect successful!!"]
try:
with connection.cursor[] as cursor:
# SQL
sql = "SELECT Dept_No, Dept_Name FROM Department "
# Execute query.
cursor.execute[sql]
print ["cursor.description: ", cursor.description]
print[]
for row in cursor:
print[row]
finally:
# Close connection.
connection.close[]
Kết quả của ví dụ
connect successful!!
cursor.description: [['Dept_No', 253, None, 80, 80, 0, False], ['Dept_Name', 253, None, 1020, 1020, 0, False]]
{'Dept_No': 'D10', 'Dept_Name': 'ACCOUNTING'}
{'Dept_No': 'D20', 'Dept_Name': 'RESEARCH'}
{'Dept_No': 'D30', 'Dept_Name': 'SALES'}
{'Dept_No': 'D40', 'Dept_Name': 'OPERATIONS'}
Mô-đun tiện ích
Lời khuyên ở đây là bạn nên tạo một module tiện ích để kết nối với cơ sở dữ liệu. Trong trường hợp tôi tạo một mô-đun có tên là "myconnutils", mô-đun này xác định hàm getConnection[] để trả về một kết nối
myconnutils. py
import pymysql.cursors
# Function return a connection.
def getConnection[]:
# You can change the connection arguments.
connection = pymysql.connect[host='192.168.5.129',
user='root',
password='1234',
db='simplehr',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor]
return connection
5- Ví dụ truy vấn
Ví dụ sau truy vấn bảng Nhân viên, Python sử dụng %s làm "phần giữ chỗ" cho tham số, không phụ thuộc vào loại tham số. Ví dụ
sql1 = "Insert into Department [Dept_Id, Dept_No, Dept_Name] values [%s, %s, %s] "
sql2 = "Select * from Employee Where Dept_Id = %s "
truy vấnVí dụ. py
# Use your utility module.
import myconnutils
connection = myconnutils.getConnection[]
print ["Connect successful!"]
sql = "Select Emp_No, Emp_Name, Hire_Date from Employee Where Dept_Id = %s "
try :
cursor = connection.cursor[]
# Execute sql, and pass 1 parameter.
cursor.execute[sql, [ 10 ] ]
print ["cursor.description: ", cursor.description]
print[]
for row in cursor:
print [" ----------- "]
print["Row: ", row]
print ["Emp_No: ", row["Emp_No"]]
print ["Emp_Name: ", row["Emp_Name"]]
print ["Hire_Date: ", row["Hire_Date"] , type[row["Hire_Date"]] ]
finally:
# Close connection.
connection.close[]
6- Chèn ví dụ
chènVí dụ. py
# Use your utility module.
import myconnutils
import pymysql.cursors
connection = myconnutils.getConnection[]
print ["Connect successful!"]
try :
cursor = connection.cursor[]
sql = "Select max[Grade] as Max_Grade from Salary_Grade "
cursor.execute[sql]
# 1 row.
oneRow = cursor.fetchone[]
# Output: {'Max_Grade': 4} or {'Max_Grade': None}
print ["Row Result: ", oneRow]
grade = 1
if oneRow != None and oneRow["Max_Grade"] != None:
grade = oneRow["Max_Grade"] + 1
cursor = connection.cursor[]
sql = "Insert into Salary_Grade [Grade, High_Salary, Low_Salary] " \
+ " values [%s, %s, %s] "
print ["Insert Grade: ", grade]
# Execute sql, and pass 3 parameters.
cursor.execute[sql, [grade, 2000, 1000 ] ]
connection.commit[]
finally:
connection.close[]
đầu ra
connect successful!!
Row Result: {'Max_Grade': 2}
Insert Grade: 3
7- Ví dụ cập nhật
cập nhậtVí dụ. py
________số 8đầu ra
connect successful!
Update! 1 rows
8- Xóa ví dụ
xóaVí dụ. py
import pymysql.cursors
# Connect to the database.
connection = pymysql.connect[host='192.168.5.134',
user='root',
password='1234',
db='simplehr',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor]
print ["connect successful!!"]
try:
with connection.cursor[] as cursor:
# SQL
sql = "SELECT Dept_No, Dept_Name FROM Department "
# Execute query.
cursor.execute[sql]
print ["cursor.description: ", cursor.description]
print[]
for row in cursor:
print[row]
finally:
# Close connection.
connection.close[]
0đầu ra
import pymysql.cursors
# Connect to the database.
connection = pymysql.connect[host='192.168.5.134',
user='root',
password='1234',
db='simplehr',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor]
print ["connect successful!!"]
try:
with connection.cursor[] as cursor:
# SQL
sql = "SELECT Dept_No, Dept_Name FROM Department "
# Execute query.
cursor.execute[sql]
print ["cursor.description: ", cursor.description]
print[]
for row in cursor:
print[row]
finally:
# Close connection.
connection.close[]
19- Thủ tục cuộc gọi
Có một số vấn đề khi bạn gọi hàm hoặc thủ tục trong Python. Tôi thiết lập một tình huống như thế này
Bạn có một thủ tục
- Get_Employee_Info[p_Emp_Id, v_Emp_No, v_First_Name, v_Last_Name, v_Hire_Date]
get_Employee_Info
import pymysql.cursors
# Connect to the database.
connection = pymysql.connect[host='192.168.5.134',
user='root',
password='1234',
db='simplehr',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor]
print ["connect successful!!"]
try:
with connection.cursor[] as cursor:
# SQL
sql = "SELECT Dept_No, Dept_Name FROM Department "
# Execute query.
cursor.execute[sql]
print ["cursor.description: ", cursor.description]
print[]
for row in cursor:
print[row]
finally:
# Close connection.
connection.close[]
2Thủ tục trên có 1 tham số đầu vào là p_Emp_Id và 4 tham số đầu ra là v_Emp_No, v_First_Name, v_Last_Name, v_Hire_Date, bạn gọi thủ tục này từ Python truyền giá trị cho p_Emp_Id sẽ nhận được 4 giá trị đầu ra. Rất tiếc, giá trị nhận được không đảm bảo là đúng [như đã nêu trong đặc tả DB-API]. Python chỉ có thể truy xuất các giá trị từ mệnh đề SELECT
Đặc tả DB-API
3import pymysql.cursors # Connect to the database. connection = pymysql.connect[host='192.168.5.134', user='root', password='1234', db='simplehr', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor] print ["connect successful!!"] try: with connection.cursor[] as cursor: # SQL sql = "SELECT Dept_No, Dept_Name FROM Department " # Execute query. cursor.execute[sql] print ["cursor.description: ", cursor.description] print[] for row in cursor: print[row] finally: # Close connection. connection.close[]
Tuy nhiên bạn vẫn có thể giải quyết vấn đề trên, bạn cần bọc thủ tục Get_Employee_Info bằng một thủ tục khác [ví dụ Get_Employee_Info_Wrap], thủ tục này trả về các giá trị từ mệnh đề SELECT