Nhiều cách. Đừng sử dụng cái rõ ràng nhất (# Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 2 với # Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 3) trong mã thực, nó mở ra cho các cuộc tấn công.DON'T use the most obvious one (# Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 2 with # Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 3) in real code, it's open to attacks.
Ở đây sao chép-paste'd từ pydoc của sqlite3:from pydoc of sqlite3:
# Never do this -- insecure! symbol = 'RHAT' cur.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol) # Do this instead t = ('RHAT',) cur.execute('SELECT * FROM stocks WHERE symbol=?', t) print(cur.fetchone()) # Larger example that inserts many records at a time purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00), ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00), ('2006-04-06', 'SELL', 'IBM', 500, 53.00), ] cur.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)Nhiều ví dụ hơn nếu bạn cần:
# Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00))Chọn với bộ lọc
Khi chọn bản ghi từ bảng, bạn có thể lọc lựa chọn bằng cách sử dụng câu lệnh "WHERE":
Thí dụ
Chọn (các) bản ghi trong đó địa chỉ là "Park Lane 38": Kết quả:
Nhập MySQL.Connector
myDB = mysql.connector.connect (& nbsp; host = "localhost", & nbsp; user = "yourusername", & nbsp; password = "yourPassword", & nbsp; cơ sở dữ liệu = "mydatabase")
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor ()
SQL = "Chọn * Từ khách hàng trong đó địa chỉ = 'Park Lane 38'"
mycursor.execute(sql)
myResult = mycursor.fetchall ()
cho x trong myResult: & nbsp; in (x)
print(x)
Chạy ví dụ »
Ký tự ký tự đại diện
Bạn cũng có thể chọn các bản ghi bắt đầu, bao gồm hoặc kết thúc bằng một chữ cái hoặc cụm từ nhất định.
Sử dụng ____ 13 & nbsp; Để đại diện cho ký tự ký tự đại diện:
Thí dụ
Chọn (các) bản ghi trong đó địa chỉ là "Park Lane 38": Kết quả:
Nhập MySQL.Connector
myDB = mysql.connector.connect (& nbsp; host = "localhost", & nbsp; user = "yourusername", & nbsp; password = "yourPassword", & nbsp; cơ sở dữ liệu = "mydatabase")
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor ()
SQL = "Chọn * Từ khách hàng trong đó địa chỉ = 'Park Lane 38'"
mycursor.execute(sql)
myResult = mycursor.fetchall ()
cho x trong myResult: & nbsp; in (x)
print(x)
Chạy ví dụ »
Ký tự ký tự đại diện
Bạn cũng có thể chọn các bản ghi bắt đầu, bao gồm hoặc kết thúc bằng một chữ cái hoặc cụm từ nhất định.
Sử dụng ____ 13 & nbsp; Để đại diện cho ký tự ký tự đại diện:
Chọn các bản ghi trong đó địa chỉ chứa từ "way":
Thí dụ
Chọn (các) bản ghi trong đó địa chỉ là "Park Lane 38": Kết quả:
Nhập MySQL.Connector
myDB = mysql.connector.connect (& nbsp; host = "localhost", & nbsp; user = "yourusername", & nbsp; password = "yourPassword", & nbsp; cơ sở dữ liệu = "mydatabase")
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor ()
SQL = "Chọn * Từ khách hàng trong đó địa chỉ = 'Park Lane 38'"
adr = ("Yellow Garden 2", )
myResult = mycursor.fetchall ()
myResult = mycursor.fetchall ()
cho x trong myResult: & nbsp; in (x)
print(x)
Chạy ví dụ »
Trang chủ »Python» Cơ sở dữ liệu »Python MySQL thực thi truy vấn được tham sốPython » Databases » Python MySQL Execute Parameterized Query using Prepared Statement
Bài viết này trình bày cách sử dụng truy vấn được tham số hóa Python hoặc câu lệnh đã chuẩn bị để thực hiện các hoạt động cơ sở dữ liệu MySQL.
Chúng tôi sử dụng truy vấn được tham số hóa để sử dụng biến Python trong truy vấn SQL. Ví dụ: -use Parameterized query to use Python variable in SQL query. For example: –
- Chúng ta thường cần chuyển các biến cho SQL Chọn truy vấn trong mệnh đề WHERE để kiểm tra một số điều kiện.
- Trong biểu mẫu đăng ký người dùng, người dùng nhập chi tiết của anh ấy/cô ấy. Bạn có thể lấy các giá trị đó trong các biến Python và chèn chúng vào một bảng.
Đối với bài viết này, chúng tôi sẽ sử dụng bảng nhân viên có trong máy chủ MySQL của tôi. Xem chi tiết cột của nó.Employee table present in my MySQL server. See its column details.
Là gì & nbsp; truy vấn được tham số hóa
Truy vấn được tham số hóa là một truy vấn trong đó trình giữ chỗ (# Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 2) được sử dụng cho các tham số (giá trị cột) và các giá trị tham số được cung cấp tại thời điểm thực thi.placeholders (# Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 2) are used for parameters (column values) and the parameter values supplied at execution time.
Hãy cùng xem ví dụ về một truy vấn được tham số hóa:
sql_parameterized_query = """Update employee set Salary = %s where id = %s"""Như bạn có thể thấy, chúng tôi đang sử dụng trình giữ chỗ (# Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 2) cho cột Mức lương và ID. Chúng ta cần cung cấp các giá trị trong các khoản giữ chỗ (# Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 2) trước khi thực hiện truy vấn. Vượt qua các biến Python tại vị trí của người giữ chỗ khi chúng tôi thực hiện truy vấn.
Chúng ta cần chuyển hai đối số sau cho hàm # Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 9 để chạy truy vấn được tham số hóa.need to pass the following two arguments to a # Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 9 function to run a parameterized query.
- Truy vấn SQL
- Một bộ của các giá trị tham số. Trong trường hợp của chúng tôi, chúng tôi cần vượt qua hai biến Python, một cho tiền lương và một cho ID.. In our case, we need to pass two Python variables, one for salary and one for id.
Sử dụng & nbsp; của truy vấn được tham số hóa và câu lệnh đã chuẩn bị
Có 4 lý do chính để sử dụng. Có bốn lý do chính để sử dụng.
Có bốn lý do chính để sử dụng.
- Biên dịch một lần: Truy vấn tham số hóa chỉ được biên dịch một lần. Khi bạn sử dụng truy vấn được tham số hóa, nó sẽ được biên dịch trước và được lưu trữ trong một đối tượng PreadStatement. Bây giờ, sử dụng đối tượng này để thực hiện cùng một câu lệnh nhiều lần một cách hiệu quả. Lưu ý: Đối với một truy vấn tiêu chuẩn, MySQL biên dịch truy vấn mỗi lần trước khi chạy nó.: Parameterized query compiled only once. When you use parameterized query, it gets precompiled and stored in a PreparedStatement object. Now, use this object to execute the same statement multiple times efficiently. Note: For a standard query, MySQL compiles the query each time before running it.
- Cải thiện tốc độ: Nếu bạn thực hiện các câu lệnh SQL nhiều lần với truy vấn được biên dịch trước, nó sẽ giảm thời gian thực hiện.: If you execute SQL statements repeatedly with a precompiled query, it reduces the execution time.
- Hoạt động tương tự với dữ liệu khác nhau: Bạn có thể sử dụng nó để thực hiện cùng một truy vấn nhiều lần với các dữ liệu khác nhau. Ví dụ: bạn muốn chèn 200 hàng vào bảng. Trong các trường hợp như vậy, sử dụng truy vấn được tham số hóa để liên tục thực hiện cùng một thao tác với một tập hợp các giá trị khác.: You can use it to execute the same query multiple times with different data. For example, you want to insert 200 rows in a table. In such cases, use parameterized query to repeatedly execute the same operation with a different set of values.
- Nó ngăn chặn các cuộc tấn công tiêm SQL..
Lưu ý: Chúng tôi đang sử dụng trình kết nối MySQL Python để thực hiện truy vấn được tham số hóa.: We are using MySQL Connector Python to execute a Parameterized query.
Cách sử dụng truy vấn được tham số hóa trong Python
Tạo một đối tượng câu lệnh đã chuẩn bị bằng cách sử dụng sql_parameterized_query = """Update employee set Salary = %s where id = %s"""0.
Nó tạo ra một con trỏ cụ thể trên đó các câu lệnh được chuẩn bị và trả về một thể hiện lớp sql_parameterized_query = """Update employee set Salary = %s where id = %s"""1.
import mysql.connector connection = mysql.connector.connect(host='localhost', database='python_db', user='pynative', password='pynative@#29') # this will retun MySQLCursorPrepared object cursor = connection.cursor(prepared=True)Ví dụ để chèn dữ liệu vào bảng MySQL bằng cách sử dụng truy vấn được tham số hóa
Đôi khi bạn cần chèn một biến python làm giá trị cột trong truy vấn chèn. Ví dụ: người dùng đã điền vào một biểu mẫu trực tuyến và nhấp vào gửi. Vì vậy, bạn cần chèn các giá trị đó vào bảng MySQL. insert a Python variable as a column value in the insert query. For example, a user has filled an online form and clicked on submit. So you need to insert those values into a MySQL table.
Đầu tiên, bạn cần đưa đầu vào của người dùng vào một biến và chuyển biến đó cho truy vấn chèn dưới dạng trình giữ chỗ (# Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 2). Tất cả các giá trị là động, tức là, tùy thuộc vào đầu vào của người dùng.
Hãy cùng xem cách sử dụng truy vấn được tham số hóa để chèn dữ liệu vào cơ sở dữ liệu MySQL bằng Python.
import mysql.connector try: connection = mysql.connector.connect(host='localhost', database='python_db', user='root') cursor = connection.cursor(prepared=True) # Parameterized query sql_insert_query = """ INSERT INTO Employee (id, Name, Joining_date, salary) VALUES (%s,%s,%s,%s)""" # tuple to insert at placeholder tuple1 = (1, "Json", "2019-03-23", 9000) tuple2 = (2, "Emma", "2019-05-19", 9500) cursor.execute(sql_insert_query, tuple1) cursor.execute(sql_insert_query, tuple2) connection.commit() print("Data inserted successfully into employee table using the prepared statement") except mysql.connector.Error as error: print("parameterized query failed {}".format(error)) finally: if connection.is_connected(): cursor.close() connection.close() print("MySQL connection is closed")Đầu ra
Data inserted successfully into employee table using the prepared statement MySQL connection is closedTham khảo các hàng tìm nạp từ bảng MySQL trong Python bằng truy vấn được tham số hóa.fetch rows from MySQL table in Python using parameterized Query.
Hiểu chương trình truy vấn tham số hóa Python MySQL
- Đầu tiên, chúng tôi đã thiết lập kết nối với MySQL từ Python.
- Tiếp theo, chúng tôi đã tạo ra một đối tượng câu lệnh đã chuẩn bị.
- Tiếp theo, chúng tôi đã tạo truy vấn SQL được tham số hóa. Trong truy vấn này, chúng tôi đang sử dụng bốn người giữ chỗ cho bốn cột.
- Tiếp theo, chúng tôi đã thêm giá trị của bốn cột theo thứ tự theo thứ tự tuần tự.
- Tiếp theo, chúng tôi đã chuyển SQL Chèn Truy vấn và Tuple sang phương thức # Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 9, hãy nhớ Tuple chứa dữ liệu người dùng theo thứ tự tuần tự của chỗ giữ chỗ.
- n Kết thúc, chúng tôi đang thực hiện các thay đổi của chúng tôi đối với cơ sở dữ liệu bằng cách sử dụng sql_parameterized_query = """Update employee set Salary = %s where id = %s"""4.
- Chúng tôi đã đặt tất cả các mã của chúng tôi trong khối Excet Try-Except để bắt các ngoại lệ nếu có.
Lưu ý: Bạn cũng có thể tạo một câu lệnh đã chuẩn bị bằng cách truyền rõ ràng & nbsp; mysqlcursorprepared & nbsp; class như một đối số trong khi tạo một con trỏ. & Nbsp; & nbsp;: You can also create a prepared statement by explicitly passing the MySQLCursorPrepared class as an argument while creating a cursor.
connection.cursor(cursor_class=MySQLCursorPrepared)Sử dụng & nbsp; dữ liệu cập nhật truy vấn được tham số hóa của bảng MySQL
Hãy cùng xem cách cập nhật bảng MySQL bằng Python. Trong ví dụ này, chúng tôi đang cập nhật mức lương của một nhân viên bằng cách sử dụng truy vấn được tham số hóa.
import mysql.connector try: connection = mysql.connector.connect(host='localhost', database='python_db', user='pynative', password='pynative@#29') cursor = connection.cursor(prepared=True) sql_update_query = """UPDATE Employee set Salary = %s where Id = %s""" data_tuple = (12000, 1) cursor.execute(sql_update_query, data_tuple) connection.commit() print("Employee table updated using the prepared statement") except mysql.connector.Error as error: print("parameterized query failed {}".format(error)) finally: if connection.is_connected(): cursor.close() connection.close() print("MySQL connection is closed")Đầu ra::
Employee table updated using the prepared statement MySQL connection is closedSử dụng truy vấn được tham số hóa và câu lệnh đã chuẩn bị để xóa dữ liệu khỏi bảng MySQL
Bây giờ, hãy để Lừa xem cách sử dụng câu lệnh đã chuẩn bị và truy vấn được tham số hóa để xóa dữ liệu bảng MySQL từ Python.
Ví dụ: khi người dùng xóa dữ liệu của họ khỏi cổng web. Trong một kịch bản như vậy, chúng ta cần sử dụng các biến đó bên trong truy vấn được tham số hóa bằng cách sử dụng trình giữ chỗ (# Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 2).
# Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 0Output::
# Multiple values single statement/execution c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', ('RHAT', 'MSO')) print c.fetchall() c.execute('SELECT * FROM stocks WHERE symbol IN (?, ?)', ('RHAT', 'MSO')) print c.fetchall() # This also works, though ones above are better as a habit as it's inline with syntax of executemany().. but your choice. c.execute('SELECT * FROM stocks WHERE symbol=? OR symbol=?', 'RHAT', 'MSO') print c.fetchall() # Insert a single item c.execute('INSERT INTO stocks VALUES (?,?,?,?,?)', ('2006-03-28', 'BUY', 'IBM', 1000, 45.00)) 1Làm việc của một truy vấn được tham số hóa
Lần đầu tiên bạn chuyển một câu lệnh truy vấn SQL cho phương thức EXECUTE () con trỏ, nó tạo ra câu lệnh đã chuẩn bị.
Đối với các yêu cầu thực hiện tiếp theo, giai đoạn chuẩn bị được bỏ qua nếu câu lệnh SQL giống nhau, tức là, truy vấn không được biên dịch lại.
- Trong sql_parameterized_query = """Update employee set Salary = %s where id = %s"""6 Python chuẩn bị câu lệnh đầu tiên, tức là truy vấn được biên dịch.
- Đối với các cuộc gọi thực thi tiếp theo của sql_parameterized_query = """Update employee set Salary = %s where id = %s"""6, truy vấn được thực thi trực tiếp với các giá trị tham số được truyền.
Bước tiếp theo
Để thực hành những gì bạn đã học trong bài viết này, vui lòng giải quyết một dự án tập thể dục cơ sở dữ liệu Python để thực hành và thành thạo các hoạt động của cơ sở dữ liệu Python.