- 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)
- 剪映短視頻剪輯零基礎一本通
- Creo Parametric 8.0中文版基礎入門一本通
- 爸媽微信e時代
- 常用工具軟件案例教程
- Spring Python 1.1
- 照相館的故事:Photoshop CC 2018調(diào)色合成精修
- BIM與Unity 3D開發(fā)實例詳解
- Illustrator平面設計立體化教程:Illustrator 2021(微課版)
- Apache Solr 3.1 Cookbook
- 神奇的中文版Photoshop CC 2017入門書
- Oracle Warehouse Builder 11g R2: Getting Started 2011
- Photoshop海報設計技巧與實戰(zhàn)
- Cassandra High Performance Cookbook
- LaTeX論文寫作教程
- Building Enterprise Ready Telephony Systems with sipXecs 4.0