- MySQL for Python
- Albert Lukaszewski, PhD
- 353字
- 2021-04-13 17:12:28
What if you want to specify a different price floor every time you run the search? What if you didn't want to use a floor but specify the price exactly? What if you wanted to reuse part of the statement and automate queries by fish name instead of retrieving all of them at once? Under such circumstances, you need to be able to handle variables in your SELECT
statements.
MySQL for Python passes variables to MySQL in the same way that Python formats other kinds of output. If we wanted to specify just the floor of the search, we would assign the variable as any other and pass it to the execute()
method as a string. Consider the following snippet from a Python terminal session:
>>> value = "7.50" >>> command = cur.execute("""SELECT * FROM menu WHERE price = %s""" %(value)) >>> results = cur.fetchall() >>> for record in results: ... print record[0], ". ", record[1], "(%s)" %record[2] ... 1 . tuna (7.50)
If we wanted the user to have the option of specifying the price precisely or using comparative expressions, we can add in that option along with making the previous variable user-defined.
>>> operation = input("operation: ") operation: '=' >>> value = input("value: ") value: 7.50 >>> command = cur.execute("""SELECT * FROM menu WHERE price %s %s""" %(operation, value)) >>> results = cur.fetchall() >>> for record in results: ... print record[0], ". ", record[1], "(%s)" %record[2] ... 1 . tuna (7.50)
As you may have surmised by now, the execute()
method is simply passing the MySQL statement as a string to _mysql
, which in turn passes it to the C database API, which in turn passes it to MySQL. This being the case, we can define the statement separately and pass it to execute()
as a variable. Consider the following replacement for the latter half of the preceding code.
>>> statement = """SELECT * FROM menu WHERE price %s %s""" %(operation, value) >>> command = cur.execute(statement) >>> results = cur.fetchall() >>> for record in results: ... print record[0], ". ", record[1], "(%s)" %record[2] ... 1 . tuna (7.50)
- Ext JS 3.0 Cookbook
- Apache OFBiz Development: The Beginner's Tutorial
- 中文版Illustrator CC實用教程
- 中文版Premiere Pro CC實用教程
- Microsoft SharePoint 2010 Power User Cookbook: SharePoint Applied
- R Graph Cookbook
- MLOps實戰:機器學習模型的開發、部署與應用
- Photoshop+Adobe Camera Raw+Lightroom(攝影后期照片潤飾實戰)
- SPSS 28.0統計分析從入門到精通(升級版)
- Adobe創意大學Photoshop CS5 產品專家認證標準教材
- 詳解AutoCAD 2022電氣設計(第6版)
- 說服力:工作型PPT該這樣做(第2版)
- ANSYS Workbench中文版超級學習手冊
- 中文版3ds Max 2022基礎教程
- Excel革命!超級數據透視表Power Pivot與數據分析表達式DAX快速入門