- MySQL for Python
- Albert Lukaszewski, PhD
- 827字
- 2021-04-13 17:12:28
We have just seen how to form a query for a generic MySQL session. While that was not particularly difficult, using MySQL for Python is even easier. For this next section, we will be working against a database fish
with a table menu
that has the following contents:
+----+----------------+-------+ | id | name | price | +----+----------------+-------+ | 1 | tuna | 7.50 | | 2 | bass | 6.75 | | 3 | salmon | 9.50 | | 4 | catfish | 5.00 | | 5 | trout | 6.00 | | 6 | haddock | 6.50 | | 7 | yellowfin tuna | 12.00 | +----+----------------+-------+
As discussed in Chapter 1, Python's interface with MySQL requires a cursor. It is through the cursor
object that we pass commands to MySQL. So, we import MySQL for Python, log into our database fish
and create the cursor as follows:
import MySQLdb mydb = MySQLdb.connect(host = 'localhost', user = 'skipper', passwd = 'mysecret', db = 'fish') cur = mydb.cursor()
To pass a command to MySQL, we use the execute()
method that we briefly covered in the last chapter. The execute()
method, as the name implies, expects an argument of what is to be executed by Python. In other words, it takes the MySQL sentence or statement as its argument. Its basic syntax is as follows:
results_variable = cursor_handle.execute('MySQL statement')
In practice, it looks like this:
command = cur.execute('SELECT * FROM menu')
As you might surmise from the previous discussion on SELECT
, this returns all rows of the table
menu.
You will notice that we did not have to specify the database in the execute()
call. This is because it was already specified in the MySQLdb.connect()
call. Each connection represents one database being accessed in the name of one user on one host. If any of those dynamics need to change, a new connection
object becomes necessary. It is possible to create a connection without declaring a database at the outset, but a database must be specified before a cursor can be created or a query made.
Unlike in the MySQL shell, the execute()
call here does not immediately return the results. They are held in system memory (RAM) until you tell MySQL for Python what you want to do with them. This is another reason why it is important to mind your use of system resources in the use of HAVING
and LIMIT
, as mentioned previously.
For the purposes of illustration, we can pull down all of the results in one go. To do this, we use the fetchall()
method of the cursor object.
results = command.fetchall()
At this point, the results have now passed from MySQL for Python into the calling program's resource matrix. The fetchall()
method returns its results as a series of tuples. Printing the value of results
shows the following:
>>> print results ((1L, 'tuna', Decimal('7.50')), (2L, 'bass', Decimal('6.75')), (3L, 'salmon', Decimal('9.50')), (4L, 'catfish', Decimal('5.00')), (5L, 'trout', Decimal('6.00')), (6L, 'haddock', Decimal('6.50')), (7L, 'yellowfin tuna', Decimal('12.00')))
This is obviously far from human-friendly. However, we can now use Python's own data-handling resources to parse it. In programming terms, we now have greater control over our data and can present it as we want. So let's create a loop to iterate through the results and print the results in a formatted way.
>>> for record in results: ... print record[0] , “-->”, record[1] , “ @”, record[2], “each” ... 1 --> tuna @ 7.50 each 2 --> bass @ 6.75 each 3 --> salmon @ 9.50 each 4 --> catfish @ 5.00 each 5 --> trout @ 6.00 each 6 --> haddock @ 6.50 each 7 --> yellowfin tuna @ 12.00 each
The last query could easily have returned more results than we could use. As mentioned previously, this is why the SELECT
command comes with a comprehensive suite of modifiers to nuance one's query and, hopefully, use a minimal amount of system resources.
To use GROUP BY
, ORDER BY
, or any of the other clauses that one can add to a SELECT
statement, one simply adds them to the MySQL statement that is passed to the execute()
method.
If you wanted to retrieve information only on fish whose price is greater than $7, you would need to sort through the data again and find the record with the matching name. Better to let MySQL do the dirty work. Using the preceding simple query (see Where under Other helpful quantifiers), we can do the following:
command = cur.execute("""SELECT * FROM menu WHERE price > 7""") results = command.fetchall() for record in results: print record[0], ". ", record[1], "(%s)" %record[2]
The results would be:
1 . tuna (7.50) 3 . salmon (9.50) 7 . yellowfin tuna (12.00)
Similar statements can be passed for each of the SELECT
clauses discussed above.
- 創意UI:Photoshop玩轉移動UI設計
- Word-Excel-PowerPoint 2010三合一從新手到高手(超值版)
- Midjourney AI繪畫藝術創作教程:關鍵詞設置、藝術家與風格應用175例
- 剪映AI視頻剪輯:AI腳本+AI繪畫+圖文生成+數字人制作
- 中文版Premiere影視編輯課堂實錄
- Software Testing using Visual Studio 2010
- After Effects CC 2019 影視后期特效合成案例教程
- Android從入門到精通
- 中文版Photoshop CS5實用教程(第2版)
- 攝影師的后期必修課(調色篇)
- Flash CC動畫制作與應用(第3版)
- Microsoft Silverlight 4 and SharePoint 2010 Integration
- 機械CAD軟件應用入門指導書
- Altium Designer 21實戰從入門到精通
- Joomla! with Flash