[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

small amount of simple Python code can easily accomplish the same result with SQLite
and Python 3.X (again, some irrelevant output lines are omitted here):


C:\...\PP4E\Dbase\Sql> python
>>> from sqlite3 import connect
>>> conn = connect('dbase1')
>>> curs = conn.cursor()

>>> curs.execute('delete from people') # empty the table
>>> curs.execute('select * from people')
>>> curs.fetchall()
[]

>>> file = open('data.txt')
>>> rows = [line.rstrip().split(',') for line in file]
>>> rows[0]
['bob', 'devel', '50000']

>>> for rec in rows:
... curs.execute('insert into people values (?, ?, ?)', rec)
...
>>> curs.execute('select * from people')
>>> for rec in curs.fetchall(): print(rec)
...
('bob', 'devel', 50000)
('sue', 'music', 60000)
('ann', 'devel', 40000)
('tim', 'admin', 30000)
('kim', 'devel', 60000)

This code makes use of a list comprehension to collect string split results for all lines
in the file after removing any newline characters, and file iterators to step through the
file line by line. Its Python loop does the same work as the MySQL load statement, and
it will work on more database types, including SQLite. We can get some similar result
from an executemany DB API call shown earlier as well, but the Python for loop here
has the potential to be more general.


Python versus SQL


In fact, you have the entire Python language at your disposal for processing database
results, and a little Python can often duplicate or go beyond SQL syntax. For instance,
SQL has special aggregate function syntax for computing things such as sums and
averages:


>>> curs.execute("select sum(pay), avg(pay) from people where job = 'devel'")
>>> curs.fetchall()
[(150000, 50000.0)]

By shifting the processing to Python, we can sometimes simplify and do more than
SQL’s syntax allows (albeit potentially sacrificing any query performance optimizations
the database may perform). Computing pay sums and averages with Python can be
accomplished with a simple loop:


SQL Database Interfaces| 1345
Free download pdf